Event Listener for Outside Click

Johnson Kow
Jan 2, 2023
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
This can be found here

I’ve noticed that this is something we use all over our platform so it’d be best to make this some kind of re-usable component to make life easier. As always, happy coding!

--

--

Johnson Kow

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