jjnrmason
jjnrmason

Reputation: 311

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

Upvotes: 2

Views: 6013

Answers (1)

Jevon Cochran
Jevon Cochran

Reputation: 1774

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

Upvotes: 3

Related Questions