To use a method as a props all the steps are described below order wise:
Project Structure: The structure of this project will look like this.
Step 1: To do this let’s make a new component named ParentComponent.js. Now let’s make the basic layout for a class component in this file.
Step 2: Now let’s set a state to greet our parent whenever this component is rendered, setting a state is not necessary, but we will do it just to make an application more dynamic. Also, let’s make an event that gives an alert whenever the parent component is rendered. Do not forget to bind the event so that the this keyword won’t return “undefined“.
Step 3: Let’s not forget to import this into our App.js file.
Step 4: Now let’s make a new component. Let’s call this ChildComponent.js, and make a simple functional component. Let’s make a simple button, and then pass the method greetParent() as a property. Essentially, the button must greet the parent when it is clicked.
Ste 5: Don’t forget to import the ChildComponent in ParentComponent. So the final code for ParentComponent will be as follows.