DEV Community

Cover image for How child component communicate with parent in React???
Deepa Chaurasia
Deepa Chaurasia

Posted on

How child component communicate with parent in React???

In that case we used reference to method as props to child component

  • Let's create a Parent component first

Image description

Here you have to notice few points

  • First you will create a parent component with constructor

  • Within the constructor you set a state called parentName with value Parent

  • Next define a method greetParent() which alert hello with the parentName initialized.

  • In the constructor you will assign this.greetParent to this.greetparent.bind(this)

Now you will create child.component.ts

We are not using state here therefore we can use a simpler component here.

  • Here you will just add a button "Greet Parent"

Image description

  • Back in parent component , you will include child component in render method .Make sure to import component at top.

Image description

  • You will render parent component in app.js

Image description

After running you will see

Image description

But nothing will happen if you click the button.

  • In ParentComponent render method you are going to add child attribute named greetHandler. And to this we assign greetParent().

Image description

  • In child component on click of button we call props.greetHandler.

Image description

  • When you click button you will see alert like this

Image description

Now we will see _how to pass a parameter when calling a parent method from child component and this is where an arrow function in the return statement is really useful_

Array function syntax is the simplest way to pass parameters from child component to parent component.

This is how you will change your child component to achieve this

Image description

  • In parent component you will receive props like this and change alert method

Image description

After this you will see the message like this while clicking on send button.

Image description

Top comments (0)