The open blogging platform. Say no to algorithms and paywalls.

How to Pass Data From One Component to Other Component in React?

Passing data from one component to another component

Props are used for passing data between the components. We usually use it to pass data from the parent component to the child component.

But what if you need to pass data from child to parent component? What if you need to pass data between siblings ??

There can be multiple ways of passing data from one component to another :

1. Using Props

You can use props to pass data from parent to child component. Example 1 illustrates the sample code for this.

|--- App.js
  |---- ParentComponent
       |----ChildComponent

2. Using React ContextAPI or State management library like Redux.

Redux or React ContextAPI gives you the functionality of central state management to manage your application. It means all the application state will be stored in a single place known as Store.

Like a traditional database represents the point of record for an application, your **Store **can be thought of as a client-side ‘single source of truth’, or database.

StoreStore

Example #1 — Using Props to pass data from Parent Component to Child Component

ParentComponent.js

ChildComponent.js

The above code snippets show how you can pass data from the Parent to Child component.

But, What if we need to pass data from Child to Parent Component ??? Let’s see this in the next!

3. Using Props as Callback Function

If you are not using any state management library like Redux or React Context API and you need to pass data from Child to Parent Component, then callbacks come into the picture.

---App
|---- Table.js
	|---- ListItem.js

Preview

src : w3schoolssrc : w3schools

**#UseCase - **When clicking on any rows on the table, Implement functionality to get that row data from the table and display on Table Main page.

**Solution - **Use Props as callback functions. Let’s see how in the example below!

I hope you now understood how data passing between React Component works. If you find any mistakes, please feel free to correct it by commenting below. I am still learning and documenting what I learn.

I would love to know your thoughts and review on this post.

You can connect with me on Twitter | Instagram.

Subscribe to my email newsletter to read more such posts.

Cheers!




Continue Learning