Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

There is XYZ component which I don't have access to. Now I want to detect if that component is clicked.

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

Reading through various articals I found this:

handleClickOutside(e){
    if (this.pop.contains(e.target)){
         // not clicked outside
    }
}

I am getting Contains is undefined as this.pop is a React component. How to solve this?

like image 444
Jagrati Avatar asked May 02 '18 11:05

Jagrati


People also ask

How do you pass ref to the functional component?

To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.

How do you set a ref in React?

Creating RefsRefs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

Can we use REF in functional component?

Creating refs However, now that React recommends functional components, and general practice is to follow the Hooks way of doing things, we don't need to use createRef() . Instead, we use useRef(null) to create refs in functional components.

What is REF IN React?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.


2 Answers

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>
  )}
}
like image 158
Mukesh Soni Avatar answered Sep 25 '22 08:09

Mukesh Soni


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} />
like image 20
David Avatar answered Sep 23 '22 08:09

David