Click outside React component
Sep 5, 2018 · 1 min read
#No plugin, package or anything required. :)
- Create a reference to your outer <Element>, here it’s ref as “node”

- Add event listener mousedown (or click) to the document whenever this component is appear on screen (eg. mount. You can also use componentWillMount()) and also don’t forget to remove the event on unmount (you can also use componentWillUnmount) too.
- Inside the event (handleOutsideClick) this.node.contains(e.target) will return true if whatever you are clicking is inside the “node” ref.

Now, You can now do whatever you feel like, close the modal, close the dropdown menu list, anything is allow.
