Little neat Trick to capture click outside React component
2 min readFeb 4, 2017
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
- Create a reference to your outer div, in this example it’s ref as “node”
- 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.
- Inside the event (handleClick) this.node.contains(e.target) will return true if whatever you are clicking is inside the “node” ref.
- 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 :)