![]() |
VOOZH | about |
In ReactJS, components are the building blocks of your user interface. Components allow you to create modular, reusable UI elements, but sometimes these components need to communicate with each other.
In this article, we will explore the different methods to pass data between components in ReactJS.
The most common way to pass data between components is through props (short for properties). Props are read-only and allow you to pass information from a parent component to its child components. When you define a child component, you can pass it data by setting its props.
First, you need to create a React App - Create a New React App
Folder Structure
Step to Run Application: Run the application using the following command from the root directory of the project
npm start
Output
👁 Screenshot-from-2023-10-06-10-46-32
In this code
In React, data usually flows from parent to child through props. But what if you need to pass data from a child component back to the parent? To achieve this, you can pass a callback function from the parent to the child. When the child component needs to send data to the parent, it calls this function with the data.
Output
In this code
When you need to pass data between sibling components (components that share the same parent), the best way is to use their common parent component as a mediator. The parent component can manage the shared state and pass it down to both child components.
For passing data among siblings, there are multiple methods we can choose from as shown below
Folder Structure
Output👁 Peek-2023-10-06-12-07
In this code
By following these methods you can easily pass data from parent to child, child to parent and also able to pass data between the siblings.