Reputation: 51
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>
);
}
}
Upvotes: 4
Views: 13496
Reputation: 2530
You can also use React.forwardingRef
method to make the Child
component able to receive and define a ref
from its parent.
Here is the documentation for the method:
https://reactjs.org/docs/forwarding-refs.html
And here is an example of how you might implement it in your code:
const Child = React.forwardRef((_, ref) => (
<h1 ref={ref}>Child Component</h1>
));
function Parent() {
var h1 = React.createRef();
React.useEffect(() => {
console.log(h1.current);
});
return <Child ref={h1} />;
}
https://reactjs.org/docs/forwarding-refs.html
I hope it helps.
Upvotes: 0
Reputation: 225
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>
);
}
Upvotes: 5
Reputation: 281636
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>
Upvotes: 3