Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

664
Views
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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!