Search code examples
javascriptreactjsdomvirtual-dom

Detecting where mouse was clicked in React component


In my React app, I have a side nav bar that opens and closes by clicking an icon.

If the nav bar is open and the user clicks anywhere outside of the nav bar, I still want to close it. How do I know if the click was outside of the nav bar? The main challange I have it to make sure that the click was not on a child node of the nav bar. So, checking just the nav like so isn't enough:

mouseDownHandler(e) {

   var container = e.target;
   if(container !== "nav-bar") {

      // Do something...
   }
};

I also need to make sure that the clicked area is not a child of nav-bar.


Solution

  • You'll need to add an event listener to the document element (e.g. in componentDidMount of your nav-bar's component) and remove it when your nav-bar is destroyed (e.g. in componentWillUnmount).

    Then you'll need to introduce a ref to get a handle of your nav-bar's element.

    All the event handling part is answered here: Detect clicks outside of specific div and all of it's children