To use a method as a props all the steps are described below order wise:
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.
Ste 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.
- ReactJS | Props - Set 1
- ReactJS | Props - Set 2
- ReactJS | State vs props
- ReactJS | Introduction to JSX
- ReactJS | ReactDOM
- ReactJS | Rendering Elements
- ReactJS | Components
- ReactJS | Components - Set 2
- ReactJS | State in React
- ReactJS | Lifecycle of Components
- ReactJS | Implementing State & Lifecycle
- ReactJS | PropTypes
- ReactJS | Importing and Exporting
- ReactJS | Calculator App ( Styling )
- ReactJS | Setting up Development Environment
- ReactJS | Conditional Rendering
- ReactJS | Lists
- ReactJS | Keys
- ReactJS | Transition Group
- How to create a Color-Box App using ReactJS?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.