we have seen how a parent component can pass down Props to its children components. Any data in the parent component when passed as Props is available in the children components. Now, what if a child component wanted to communicate with the parent component? BINGO, we still use props. But this time we pass in a reference to a method as Props to the child component
To do this let’s make a new component named Parent.js . Now let’s make the basic layout for a class component and add a constructor in this file ,Within the constructor we set a state called Parent name with the value 'I am Parent 🤟',along that define a method inviteParent which simply alerts hello by the Parent name which is set in the state so hello ,since we are using this keyword in the method, we need to bind this method
export class Parent extends Component {
constructor(props) {
super(props)
this.state = {
first:'I am Parent'
}
this.inviteParent =this.inviteParent.bind(this)
}
inviteParent(child){
alert(`HELLO ${this.state.first} `)
}
render() {
return (
<div>Parent </div>
)
}
}
export default Parent
Next we will create another file called child.js as a functional component and include the child component in the render method in parent component
export class Parent extends Component {
constructor(props) {
super(props)
this.state = {
first:'I am Parent'
}
this.inviteParent =this.inviteParent.bind(this)
}
inviteParent(){
alert(`HELLO ${this.state.first} `)
}
render() {
return (
<div>
<ChildComponent/>
</div>
)
}
}
want to execute the method defined in the Parent component. Basically, a child component calls a Parent components method and as I mentioned already, this is achieved using Props.In Parent component we add an attribute to the child component ,call the attribute inviteHandler
render() {
return (
<div>
<ChildComponent inviteHandler={this.inviteParent}/>
</div>
)
}
Now in the child component, on click of this button we simply call Props inviteHandler
function ChildComponent(props) {
return (
<div>
<button onClick={props.inviteHandler}> CHILD</button>
</div>
)
}
export default ChildComponent
Going to the browser. Click on the button. And you can see the alert hello, parent. So we have successfully called a method in the parent component from a button in the child component by passing the method as props to the child component
Conculsion 🤙
So this is pretty much how you pass methods as props in react components. In the parent component, define the method on the child component tag pass the method as a prop in the child component, access the method using the props object.
Top comments (0)