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 => (
  <div>
    <div>{project.name}</div>
    <div
      onClick={() => setDropdownId((prevState) => (
        prevState === project.id ? null : project.id)
      )}
    >
      Show
    </div>
    {dropdownId === project.id && (
      <ul className="dropdown">
        <li>option</li>
      </ul>
    )}
  </div>
))

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: