this.node.contains does not work if this.node is a ref to react component

You can use ReactDOM.findDOMNode to get a reference to the DOM node -

handleClickOutside(e) {
    if(this.pop) {
        const domNode = ReactDOM.findDOMNode(this.pop)
        if(this.pop.contains(e.target)) {
            //
        }
    }
}

Since findDOMNode is deprecated in React 16 and would be removed in future versions - another thing you can try is wrapping the XYZ component inside a div and check for click on that div.

render () {
   return(
    <div onClick={this.handleContainerClick}>
      <XYZ className="abc" ref={node => {this.pop = node}} /> // Note, I don't have access to XYZ component
    </div>
  )}
}

The current answer is to use the current attribute.

myRef = React.createRef();

const checkIfContains = e => {
    if (myRef.current.contains(e.target)) {
        doSomething();
    }
}

<div ref={myRef} onClick={checkIfContains} />

Tags:

Reactjs