How to check if a user clicked inside the current component?

I have a component called Dialog in which I attach an event listener to mouse clicks on a window object.

 componentDidMount() { document.addEventListener('click', this.handleClick); } componentWillUnmount() { document.removeEventListener('click', this.handleClick); } 

How can I detect (in the handleClick function) whether a click has been handleClick inside the component or outside? Note that this dialog box contains various elements and child components.

+7
reactjs
source share
1 answer

parent.contains(child) is your friend. This solution using refs may not be ideal, but just using this does not work, as it is not a proper DOM node. I use React 15 here, so keep in mind that in earlier versions you would need to use .getDOMNode() for the parent.

 class Dialog extends React.Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); } componentDidMount() { document.addEventListener('click', this.handleClick); } componentWillUnmount() { document.removeEventListener('click', this.handleClick); } handleClick(e) { if (this.node.contains(e.target)) { console.log('You clicked INSIDE the component.') } else { console.log('You clicked OUTSIDE the component.') } } render() { return( <span ref={node => this.node = node}> Level 0<br/> <span> Level 1.<br/> <span>Level 2.</span> </span> </span> ); } } ReactDOM.render(<Dialog/>, document.getElementById('View')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="View"></div> 
+10
source share

All Articles