React JS Method As Props

In react we can pass method/function as props, which is helpfull for handel parent component's event in child component or multiple child component.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. ParentComponent

ParentComponent
import React, { Component } from 'react'; import ChildComponent from './components/ChildComponent'; class ParentComponent extends Component { constructor(props) { super(props) this.state = { name:'React' } } clickHandler() { alert(`Hello ${this.state.name}`); } render() { return( <div> <ChildComponent clickHandler={clickHandler} /> </div> ); } }

In above code, one method created as clickHandler, this method passed in child component as props. now, see below code for childcomponent.

2. ChildComponent

ChildComponent
import React, { Component } from 'react'; const ChildComponent = props => { return <button onClick={props.clickHandler}>Show alert message</button> } export default ChildComponent;

In child components use props.chickHandler in onClick event of button. Now, click on 'show alert message' button it will show message as 'Hello React' which is written in parent component. So, we have successfully called a method of parent componnent from a button of child component.

We can also, pass parameter in this props. see at below example. change in ParentComponent file as per below,

Example
clickHandler(childName) { alert(`Hello ${this.state.name} ${childName}`); }

change in childComponent as per below.

Example
<button onClick={() => props.clickHandler('JS')}>Show alert message</button>

By click on button this will show 'Hello React JS'. Here, 'JS' is passed as parameter from ChildComponent.

So, In this way we can use method as props in react js.

 

← Previous

Next →