Click outside React component

Ashish Talele
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.

Ashish Talele

Written by

Software Engineer at QuickHeal

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