Pass React Ref from parent to child in order to get DOM element

Spacemoose picture Spacemoose · Mar 1, 2019 · Viewed 8.8k times · Source

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?

Answer

Shubham Khatri picture Shubham Khatri · Mar 1, 2019

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();
}