Coding does not feel as cool as this photo looks (sometimes)

There have been many times where I’ve wanted to ‘do something’ when clicking outisde of an element. For example, if there is a dropdown that is open, clicking outside of it should close it. Clicking outside of a modal should close it. So the question is how do we do that?

  • Add a reference to the element of interest (ex: Dropdown container, modal container)
  • Add a useEffect, add event listener, and remember to unmount your event listener logic.
  • Inside of your callback, check to see if the event target exists outside of the reference node. If it does, then insert the logic you’d like to run when clicked outside

--

--

Johnson Kow

Software Engineer based out of NYC. Learning more about programming everyday 👍