Little neat Trick to capture click outside React component

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….

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( 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

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