Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 223
Spacemoose Avatar asked Mar 01 '19 08:03

Spacemoose


People also ask

How do you pass reference from parent to child in React?

The forwardRef method in React allows parent components to move down (or “forward”) refs to their children. ForwardRef gives a child component a reference to a DOM entity created by its parent component in React.

How do you get the DOM element in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.

How do you pass data from parent to child in React functional component?

Firstly, let's pass data between a parent component and a child component. . First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function.


1 Answers

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();
}
like image 56
Shubham Khatri Avatar answered Sep 26 '22 03:09

Shubham Khatri