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?
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.
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.
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.
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.
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} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With