Home > database >  React: Reset class when click on others elements
React: Reset class when click on others elements

Time:05-24

I've created an hamburger menu that change the class name when a button is click it. This works

const Hamburger = ()=> {
    const [show, setShow] = useState(false);
    function showIt() {
        setShow(!show);
    }
    return (
        <HamburgerIcon className={show ? 'menu-open' : ' menu-close '} onClick={showIt}>
            <span></span>
        </HamburgerIcon>
    )
}
export default Hamburger;

Default state for the hamburger is ".menu-close" if you click toggle to ".menu-open". But when I click in a link inside the menu, the menu remain open.

What I want to achieve is to change the class also if a link in the menu is click it.

Any suggestion on what I should do here?

Thank you!!

CodePudding user response:

Add the showIt function to the link inside the menu

Code:

const Hamburger = ()=> {
    const [show, setShow] = useState(false);
    function showIt() {
        setShow(!show);
    }
    return (
        <HamburgerIcon className={show ? 'menu-open' : ' menu-close '} onClick={showIt}>
          <a href="/some/path" onClick={showIt}>
          Example
          </a>
        </HamburgerIcon>
    )
}
export default Hamburger;

CodePudding user response:

You can lift the state up to the parent component.

In the example below, I've lifted the state up to the lowest common ancestor component of Menu and Hamburger components. And then passed down the state via props.

function Hamburger({ isOpen, onClick }) {
  return <button onClick={onClick}>Menu {isOpen ? "↓" : "→"}</button>;
}

function Menu({ isOpen, menuItems, onClick }) {
  if (!isOpen) {
    return null;
  }
  return (
    <ul>
      {menuItems.map((item, index) => (
        <li key={index}>
          <button onClick={onClick}>{item}</button>
        </li>
      ))}
    </ul>
  );
}

function App() {
  const [isOpen, setIsOpen] = React.useState(false);

  const handleClick = () => setIsOpen(!isOpen);

  return (
    <nav>
      <Hamburger isOpen={isOpen} onClick={handleClick} />
      <Menu
        isOpen={isOpen}
        onClick={handleClick}
        menuItems={["Home", "About", "Contact"]}
      />
    </nav>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
ul {
  list-style: none;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>

  • Related