Search code examples
reactjsref

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.


Solution

  • 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