'Pass React Ref from parent to child in order to get DOM element
I have a parent and a child component. I need to access the parent's HTMLelement in the child component.
I have a working but unclean solution involving
this.setState({ domNode: ReactDOM.findDOMNode(this) }); in the parent's componentDidMount which is just wrong on many levels.
How can i do this using createRef() in the parent to pass its ref as a prop to the child and then how do i get the DOM node with type HTMLElement from the ref?
Solution 1:[1]
The best solution that doesn't involve any hack would be to pass a function from parent to child that return the ref of the element to be access
Parent:
constructor(props) {
super(props);
this.domElem = React.createRef();
}
getElem = () => {
return this.domElem;
}
render() {
return (
<div>
<div id="elem" ref={this.domElem}>Test Elem</div>
<Child getParentElem={this.getElem}/>
</div>
)
}
Child:
getParentRef = () => {
const elem = this.props.getParentElem();
}
Solution 2:[2]
The solution of @Shubham Khatri is proper to be mentioned. The small correction I want to show, there is no need to invoke a callback function getElem() from child to parent to receive the parent's ref. It can be passed directly the ref to child <Child getParentElem={this.domElem}/>
I see few user complaining to receive {current: null} at child. Please check if the components UI is delivered by a framework, like e.g. Semantic-UI. Probably there could be other methods to hook a ref from a component. In Semantic-UI have to be wrapped the parent component in <Ref innerRef={ ... }> ... </Ref>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shubham Khatri |
| Solution 2 |
