Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the onClick function works inside the jsx and don't work outside the return statement

Why the onClick function works inside the jsx and don’t work outside the return statement

import React, { useState } from "react";
    
function Menu({ items }) {
      const [displayChildren, setDisplayChildren] = useState({});
      console.log(displayChildren);
    
      return (
        <ul>
          {items.map((item) => {
            return (
              <li key={item.title}>
                {item.title}{" "}
                {item.children && (
                  <button
                    onClick={() => {
                      setDisplayChildren({
                        ...displayChildren,
                        [item.title]: !displayChildren[item.title],
                      });
                    }}
                  >
                    {displayChildren[item.title] ? "-" : "+"}
                  </button>
                )}
                {displayChildren[item.title] && item.children && (
                  <Menu items={item.children} />
                )}
              </li>
            );
          })}
        </ul>
      );
    }
    export default Menu;

but when I make the onclick function outside as such it does not do anything

  const buttonHandler = (item) => {
    setDisplayChildren({
      ...displayChildren,
      [item.title]: !displayChildren[item.title],
    });
  };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const buttonHandler = (item) => // etc

This function expects to be passed in an item, but when the click happens, react will pass in the click event object. It doesn’t know about the item. So you will need to pass in the item yourself, by creating another function:

<button onClick={() => buttonHandler(item)}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading