Search code examples
javascriptreactjsecmascript-6react-componentreact-ref

Can't get Child Component ref object from their parent React JS


I want to reference a <div> and a <span> component from the child to the parent.
So i code something like:

class Parent extends Component {
    childRef = React.createRef()

    componentDidMount(){
      const childRef1 = this.childRef.current.innerRef1
      const childRef2 = this.childRef.current.innerRef2
     
      //... compute with the references childRef1 and childRef2
  }
 
  render(){
    return(
      <ChildComponent ref={this.childRef} />
    )
  }
}

Inside the child i got something like:

 class ChildComponent extends Component {
    innerRef1 = React.createRef()
    innerRef2 = React.createRef()
    
 
  render(){
    return(
      <div ref={this.innerRef1}>
         <span ref={this.innerRef2}></span>
      </div>
    )
  }
}

I want to get the properties of those tags. Things like getBoundingClientRect(), scrollTop,etc; but from the Parent component because i can't compute it from the ChildComponent componentDidMount because those component aren't rendered yet.

That's is my current result from browser console: enter image description here

As you can see, the current object shows me a null value, but inside you can see all the properties that i want to get.


Solution

  • As you want to get the properties of those tags like getBoundingClientRect(). I have provided the example where I called getBoundingClientRect() using ref and also I set a string into innerText of span. Please check it.

    Parent Component Example

    import React from "react";
    import ChildComponentExample from "./ChildComponentExample";
    
    export default class ParentComponentExample extends React.Component {
        childRef = React.createRef();
    
        componentDidMount() {
            const childRef1 = this.childRef.current.innerRef1;
            const childRef2 = this.childRef.current.innerRef2;
    
            console.log(childRef2, 'childRef2');
            childRef2.current.innerText = 'This is SPAN';
            const rect = childRef1.current.getBoundingClientRect();
            console.log(rect, 'rect');
        }
    
        render() {
            return (
                <ChildComponentExample ref={this.childRef}/>
            )
        }
    }
    

    Child Component Example

    import React from "react";
    
    export default class ChildComponentExample extends React.Component {
        innerRef1 = React.createRef();
        innerRef2 = React.createRef();
    
        render() {
            return (
                <div ref={this.innerRef1}>
                    <span ref={this.innerRef2}/>
                </div>
            )
        }
    }