DEV Community

Kyuhee Lee
Kyuhee Lee

Posted on • Edited on

Communication Between the Parent Component and the Child Component.

Image description

React uses components to pass data from a parent to a child or uses callback function to let the child component communicate with the parent component.

Props
Props is a type of properties and arguments that pass down data or value from the parent component to the child component.

Lets look at an example below to find out which one is a parent and which one is a child first.

Image description

The Apps is the parent component and Header and Home are the Child component.

In this example, the Apps is passing the prop articleText and the commentText to each Child component with a value. The Home component will look like the example below to use the object (props) to access and render values

Image description

If you console.log (props) then you will see the message "Phase2 React project by Lee" inside of the Home component.

There is another way to pass the data calls Destructuring props.

Destructuring props.

Destructuring props helps developer to write easier, clean, and more readable code. It can assign a variable or can call more than one property.

Here is an example without using destructuring props.

Image description

Since we called props an object so we have to pass props to every property like props.img, props.name, props.description, and props.texture.

However, if we wrote a code with destructuring props, we can call these properties directly from the (props) object to write a simple readable code like the image below.

Image description

React can only pass props from parent to child, not between children or from child to parent. But what if we want to send a data opposite way? In this time, we can use a callback function in a child component to affect data in the parent component.

useState
useState is a React Hook that allow us to use a callback function. It's a function passed as an argument to another function, allowing the parent-child can communicate each other. In React, most callback functions are used as event handlers to pass data between components to continue rendering and updating them.

Before using useState in our component, we have to import useState from react like the image below on line 4.

Image description

The example above, the handCountClick function is passing an onClickTask event handler to the Home (child) component.

Image description

The Home component will look like image above, we are now passing onClickTask function in child component to make changes in App (parent) component.

Conclusion
Now we learned how the parent and child components are communicating with each other. Props is passing down the data from top to bottom and if we want to do the reverse then we should use a callback function. Thank you for your time reading this post, I hope this helped you to understand how React components communicate each other.

Top comments (0)