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:

importReact, { Component } from'react';
// import Child component hereexportdefaultclassParentextendsComponent {
  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 casethis.setState({
      myRequestedRefs: childRefs
    });
    console.log(this.state.myRequestedRefs); // this should have *info*, *contact* as keys
  }    

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

Child Component:

importReact, { Component } from'react';

exportdefaultclassChildextendsComponent {
  constructor(props){
    super(props);
    // ...
  }    

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

  }    

  render() {
    return (
      <divclassName="homeMain"><sectionref="info"><Info/></section><sectionref="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"