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>
);
}
}
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>
);
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With