Home > OS >  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

Time:02-18

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],
    });
  };

CodePudding user response:

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)}>
  • Related