Passing data in React between Parent and Child in Functional Components

Passing data in React between Parent and Child in Functional Components

For beginners who started out in ReactJS, passing data between components may be confusing. I struggle this when I first started out. There are two ways of passing data in React components

  1. From Parent to Child
  2. From Child to Parent


Passing Data from Parent To Child Components

When you are passing data from, you can use props to transfer the data. The Child will access the data in the props.

An example like this where you want to transfer a message from Parent to Child.


We have the Parent and Child components (Link to Github Repo)

Parent.js

No alt text provided for this image

Child.js

No alt text provided for this image

The Parent pass the data in message, and the Child got the data in props.message. Props pass the state from Parent to Child.


Passing Data from Child To Parent Components

Passing data from child to parent is more tricky. This is different compare to passing data from Parent to Child.


  1. Create a callback method. This method will get the data from the Child to Parent.
  2. Pass your data as props in Child. The Child will call the Parent callback using props.
  3. The callback method in the Parent will act as prop to the Child component.


Here are the Child and Parent components (Link to Github Repo)

Parent.js

No alt text provided for this image


Child.js

No alt text provided for this image


Conclusion

We learn how to pass data between Parent and Child in functional component. Knowing this is essential to build an app in ReactJS. The Github repo is here.




Denys Stepaniuk

Front-end developer (JS, React, HTML5, CSS3 )

1y

Thank you very much 😀

Juan Pablo Azambuyo

Front-End Developer | ReactJS | NodeJS | Typescript

1y

Thank you very much !! This saves me !!

Yuri Ancelmo

Remote-only | Senior Software Developer | .Net Core 6.0 | React.js | AWS | RabbitMq | PL SQL | Docker

1y

I appreciate your article, and I found it using Google, when I was looking for a solution to pass a event click from the parent to the child. So in cases that you have a FabButton on parent component, and you click on it, I'm looking for a way to notify children to do something with this information. What will you think that is the best approach ?

Prabhjot Arora

Ex-Intern @ ZealYug | Full Stack Developer | MCA Student

2y

Amazing...I looked around stackoverflow and other platforms for Child To Parent Data Passing, but didn't understand. After I saw this, it's totally clear. Thank you for making this so simple.

Syed Raza Ur Rehman Shah

Software Engineer | JavaScript | TypeScript | React Js | Angular | Node Js | Express Js | MongoDB | Web Developer | MySQl |MariaDB

2y

You done a good job bro.

To view or add a comment, sign in

Others also viewed

Explore topics