alling a child component's method from parent component is very easy. In this article, we'll have a parent component and a child component, and we will call the child component's function from the parent component.
In this what we'll do is, In the parent component, we'll have a state callChildReset and in this parent component, we'll update ( increment ) this state value using setState on the click of the Reset button.
And this state key callChildReset will be passed in Child component in the render method of the parent component. when the value of callChildReset gets to update the render function will call and the updated value of callChildReset will pe passed in Child component. And in the Child component, in componentDidUpdate lifecycle hook, we'll check if the props are updated then we'll call the child component's method reset.
Let's dive into the codes:
In the Child component, in componentDidUpdate(), the comparison is not happening in a standard way. To see the standard way of props comparison in componentDidUpdate() Click here.
Let's have a look on other way to do this:
In this, to execute a function of a child component, you will need to use Refs.
React supports a special attribute
that you can attach to any component, Here we'll attach this with child component like ref="child" that's the ref attribute, it takes a callback function, and you can access
functions of the child component in the parent accessing this.refs.REF_NAME.METHOD_NAME.
That's it, now we can call a child's component methods from the parent component.
If you found this article is helpful, then please share this article's link to your friends to whom this is required, you can share this to your technical social media groups also. You can follow us on our social media page for more updates and lates article updates.