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

222
Views
Dropdown menu in React js

I am currently building a dropdown based design in React. When I click any one of the buttons, the dropdown appears. Now when I click anywhere inside the dropdown, I want the dropdown to stay. But based on my current implementation, when I click on the dropdown, the dropdown goes away. I can fix this behaviour by prop drilling but the code gets ugly. How can I implement this cleanly?

export default function SearchFilter() {
  const [selected, setSelected] = useState(null);

  const handleClick = (e) => {
    const id = e.target.id;
    setSelected(id);
    }
  };
  const clearSelected = (e) => {
    if (e.target.id) return;
    setSelected(null);
  };
  useEffect(() => {
    window.addEventListener("click", clearSelected);
    return () => window.removeEventListener("click", clearSelected);
  });
  return (
    <div onClick={handleClick}>

      <MenuItem id={1} className={selected == 1 ? "shadow-xl" : ""}>

          <MenuDropdown className={`absolute left-0 top-full translate-y-3 ${
            selected != 1 && "hidden" />

      </MenuItem>

      <MenuItem id={2} className={selected == 2 ? "shadow-xl" : ""} />
      <MenuItem id={3} className={selected == 3 ? "shadow-xl" : ""} />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I know of a fancy hook for clicking outside of something, will probably help out and I keep seeing it referred to for this, here: https://usehooks.com/useOnClickOutside/

about 4 years ago · Juan Pablo Isaza Report

0

You shouldn't handle the close like that, you can't control where you click with that listener. You should use material ui components because the components have all these functions and many others that you didn't think of right now.

If you want to implement it yourself, you should add a ref to dropdown and create a hook for clicking outside the component.

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!