horgen
horgen

Reputation: 2203

How to get the DOM ref of a child class component in a parent class component

I'm having a hard time understanding the docs on how to access the DOM ref of a child class component from the parent class component.

Parent.js:

import Child from './Child';

class Parent extends Component {
    constructor(props) {
        super(props);
        this.refOfTheParent = React.createRef();
    }

    componentDidMount() {
        const parentDOM = this.refOfTheParent.current;
        //const childDOM = ???;
    }

    render() {
        return (
            <div ref={this.refOfTheParent}>
                <Child />
            </div>
        );
    }
}

export default Parent;

Child.js:

class Child extends Component {

    render() {
        return (
            <div>Child component</div>
        );
    }
}

export default Child;

Could someone please finish this code for me where childDOM in Parent::componentDidMount() has the DOM ref of <Child />.

Bonus: How would it look if Parent AND Child are both connected with react-redux connect.

Upvotes: 0

Views: 2944

Answers (2)

Dhaval Patel
Dhaval Patel

Reputation: 7601

you can pass the ref in props in child component like

import React,{Component} from 'react';
import Child from './Child';
class Parent extends Component {
    constructor(props) {
        super(props);
        this.refOfTheParent = React.createRef();
        this.childRef=React.createRef();
    }

    componentDidMount() {
        const parentDOM = this.refOfTheParent.current;
         const childDom=this.childRef.current;
         console.log(childDom);
        //const childDOM = ???;
    }

    render() {
        return (
            <div ref={this.refOfTheParent}>
                <Child childRef={this.childRef}/>
            </div>
        );
    }
}
export default Parent

Child Component

import React,{Component} from 'react';
class Child extends Component {
    render() {
        return (
            <div ref={this.props.childRef} id="1">Child component</div>
        );
    }
}

export default Child;

Demo

Upvotes: 0

tubu13
tubu13

Reputation: 934

You can use forwardRef

class Child extend React.Component{
   render() {
      return (
        <div ref={this.props.forwardRef}> Child component </div>
      )
   }
}

export default React.forwardRef((props, ref) => <Child {...props} forwardRef={ref} />)

Then in parent

constructor(props) {
  // ...
  this.childRef = React.createRef();
}

render() {
    return (
       <div>
         <Child ref={this.childRef} />
       </div>
    )
}

more info here

Upvotes: 2

Related Questions