Reputation: 399
Here is the component hierarchy I have.
<Parent>
<Child1>
<Child2>
</Child2>
</Child1>
<Parent>
In Child2 component, there is a function called handlePatch(). I need to call it from Parent component but not sure how to do it. What is the best approach for this?
Thanks.
Upvotes: 2
Views: 671
Reputation: 281626
you could pass on a ref
of the Child
component to the Parent
as props and access that to call the function like
class App extends React.Component {
constructor() {
super();
this.child = null;
}
render() {
return (
<Parent childRef={this.child}>
<Child ref={(ref) => this.child = ref}/>
<Parent>
)
}
}
class Parent extends React.Component {
myfunc = () => {
//call child function
this.props.childRef.handlePatch();
}
}
However you can try to avoid it by restructuring your code a little better and directly calling the function in Child
from the container of Parent
component.
Upvotes: 1