Hide dropdowns in loop on click outside

I have an array of values which would render a list with a dropdown menu. I would show/hide the dropdown on click of an element.

 projectData.map(project => (
      onClick={() => setDropdownId((prevState) => (
        prevState === project.id ? null : project.id)
    {dropdownId === project.id && (
      <ul className="dropdown">

How can I hide the opened dropdown on outside click? I tried with ref but is not working as expected as the elements are in a loop.

Read more here: https://stackoverflow.com/questions/68482248/hide-dropdowns-in-loop-on-click-outside

Content Attribution

This content was originally published by Akhil Chandran at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: