Little neat Trick to capture click outside React component

Pitipat Srichairat
Feb 4, 2017 · 2 min read

Note: I’ve revisited this problem again, but with React Hook, here

If you have tried to develop your own dropdown, modal or popover. I’m guessing you’ve been in this situation. “How do I capture clicking outside component so I can close it??”

I feel you bro….

Image for post
Image for post

I’m gonna present you one simple snippet, which is really handy to solve the issue.

So what we need is

  1. Create a reference to your outer div, in this example it’s ref as “node”
  2. Add event listener mousedown (or click) to the document whenever this component is appear on screen (eg. mount) and also don’t forget to remove the event on unmount too.
  3. Inside the event (handleClick) this.node.contains(e.target) will return true if whatever you are clicking is inside the “node” ref.
  4. Now you have it, you can now do whatever you feel like, close the modal, close the dropdown menu list, anything is allow :D
Image for post
Image for post
Image for post
Image for post

No plugin, package or anything required. Happy coding :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store