In this blog post we will describe how you can pass some data from one component to another component or parent component to child component.
Lest create two component one is parent.js and second one is child.js, you can give any name to these components.
After creating these file on src folder, lets check all files code and try to understand whats happening inside the code.
Index.js File
App.js File
Parent.js File
Child.js File
Let’s understand what’s happening here.
Inside Index.js file we are calling App.js file in JSX, so App file data will appear first when project gets load.
Inside App.js file we are creating two variables with some data to display for parent and child component files.
We are also importing Parent.js file and calling inside the App.js file JSX code.
These sendParentData and sendChildData are properties which we are passing to parent component.
Inside Parent.js file we are recieving these values inside the props variable, this props variable is a object of all these properties those we are sending in App.js file by passing inside the Parent tag.
This props variable has data in object format like below
so we can easily get this object data and display in html by the help of data binding.
Simmilar we are doing with Child component and passing data which is coming from the app component file and then passed to child component from the parent component.
Now in simmilar way we can get this data using props and display in child component JSX.
This way we can pass data from one component to another component so this communication is called parent to child communication as we are importing components and passing data to them.
Lets check the output for this code.
As we are importing parent component in app component and inside parent component we are importing child component so both component will display on same page which is app component JSX output.
For any question and doubts you can comment below and also if you want a blog on specific topic please feel free to comment.
2 Comments