简体   繁体   中英

Close menu when clicking outside the React component

I have a menu component which I want to close when I click anywhere on the page if it's open.

Is there a way to close the menu without the need for an event listener being added to the document and checking the event.target .

There is no way to send the close function back upto the parent component as it lives on a separate Route .

Navbar
-> MenuComponent
RouteView
-> MainContent

Yes. This is easily accomplished by wrapping the component in the ClickAwayListener provided by material ui. Then you pass a function to the onClickAway attribute and that should close your menu for you. I've provided a template below and you can also check out the MUI docs :

import ClickAwayListener from '@mui/material/ClickAwayListener';

export default function MenuComponent() {
  const [open, setOpen] = useState(false);

  const handleClick = () => {
    setOpen(!open);
  };

  const handleClickAway = () => {
    setOpen(false);
  };

  return (
    <ClickAwayListener onClickAway={handleClickAway}>
      <Box>
        <button type="button" onClick={handleClick}>
          Open menu dropdown
        </button>
        {open ? (
          <Box>
            Click me, I will stay visible until you click outside.
          </Box>
        ) : null}
      </Box>
    </ClickAwayListener>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM