How to pass data from one component to other component in ReactJS ?
In this article, We are going to see how to pass data from one component to another component. We have multiple ways of passing data among components. We can pass data from parent to child, from child to parent, and between siblings. So now let’s see how can we do so.
Creating React Application:
- Step 1: Create a React application using the following command.
npx create-react-app myapp
- Step 2: After creating your project folder i.e. myapp, move to it using the following command.
Project Structure: It will look like the following. We have created two Components named Child.js and Parent.js as shown below.
We have created two Components named Child.js and Parent.js as shown in the above structure.
Passing data from Parent to Child:
For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only.
Example: The following example covers how to pass data from Parent to Child Component in ReactJS.
Step to Run Application: Run the application using the following command from the root directory of the project:
Passing data from Child to Parent Component:
For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component.
Example: The following example covers how to pass data from Child to Parent Component in ReactJS.
Passing data between Siblings:
For passing data among siblings, there are multiple methods we can choose from as shown below:
- Combination of the above two methods (callback and use of props).
- Using Redux.
Example: In this example, we are passing data between siblings using ContextAPI. Hence, we have a different project for this.
Project Structure: It will look like the following. We have created two Components named Child1.js and Child2.js as shown below.
Please Login to comment...