Skip to content Skip to sidebar Skip to footer

How To Get Refs From Another Component In React JS

The code in main App component is as follows : class App extends Component { componentDidMount(){ console.log(this.ref); debugger; } render() { return (

Solution 1:

The React's main idea is passing props downward from parent to children (even to deeper levels of children - grandchildren I mean)

Therefore, when we want the parent to do something which is triggered from (or belongs to) the children, we can create a callback function in the parent, then pass it down to children as props

For your preference, this is a demonstration on how to pass callback functions downward through many levels of children and how to trigger them:

Force React container to refresh data

Re-initializing class on redirect

In your case, you can access refs from children components as follows: (using string for ref - as you stated)

Parent Component:

import React, { Component } from 'react';
// import Child component here

export default class Parent extends Component {
  constructor(props){
    super(props);
    // ...
    this.getRefsFromChild = this.getRefsFromChild.bind(this);
  }    

  getRefsFromChild(childRefs) {
    // you can get your requested value here, you can either use state/props/ or whatever you like based on your need case by case
    this.setState({
      myRequestedRefs: childRefs
    });
    console.log(this.state.myRequestedRefs); // this should have *info*, *contact* as keys
  }    

  render() {
    return (
      <Child passRefUpward={this.getRefsFromChild} />
    )
  }  
}

Child Component:

import React, { Component } from 'react';

export default class Child extends Component {
  constructor(props){
    super(props);
    // ...
  }    

  componentDidMount() {
    // pass the requested ref here
    this.props.passRefUpward(this.refs);

  }    

  render() {
    return (
      <div className="homeMain">
        <section ref="info"> <Info/> </section>

        <section ref="contact"> <Contact /> </section>
      </div>          
    )
  }  
}  

Solution 2:

ref is property of each this.props.children hence you can access ref of child component in parent via ref property on this.props.children

Make sure you access ref after componentDidMount

Edit :

Try below set of code if this works :

var myChild= React.Children.only(this.props.children);
var clone = React.cloneElement(myChild, { ref: "myRef" });

Post a Comment for "How To Get Refs From Another Component In React JS"