Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs How to access child components refs from parent

How to access the refs of children in a parent to do something with them in the parent function?

class Parent extends Component {

  someFunction(){
  // how to access h1 element of child in here ??
  }

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



class Child extends Component {
  render() {
    return (
      <h1 ref="hello">Hello</h1>
    );
  }
}
like image 363
Amit M Avatar asked Feb 05 '23 22:02

Amit M


2 Answers

To add to Shubham's answer, the child refs have to be accessed inside of componentDidMount() inside parent. Something like:

class Parent extends React.Component {
    componentDidMount(){
        var elem1 = this.refs.child1.refs.childRefName;
    }

    return (
    <View>
      <Child1 ref='child1'/>
      <Child2 />
      <Child3 />
    </View>
    );
}
like image 116
Subhadeep Banerjee Avatar answered Feb 07 '23 11:02

Subhadeep Banerjee


You can access the child refs by providing a ref to the child element and accessing it like ReactDOM.findDOMNode(this.refs.child.refs.hello)

In your case the child component doesn't begin with Uppercase letter which you need to change.

class App extends React.Component {
   componentDidMount() {
       console.log(ReactDOM.findDOMNode(this.refs.child.refs.hello));
   
   }
   render() {
      return (
        <Child ref="child"/>
      );
     }
    }
class Child extends React.Component {
     render() {
      return (
        <h1 ref="hello">Hello</h1>
      );
     }
    }
    
    
    ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<divi id="app"></div>
like image 28
Shubham Khatri Avatar answered Feb 07 '23 11:02

Shubham Khatri