Passing Data in React

React-A Javascript library to create an application.

To create that application, data needs to be passed around.

React has a one-way data flow. But data needs to be passed both ways. Data would need to be passed from parent to child and child to parent. With react’s one way data flow, this makes going both directions hard.

The easiest way to pass data is from Parent to Child:

The way to pass data down from parent to child is by using props. Props is just a representation of the data that gets passed down to the child. If the data is accessed in the parent, then the child needs that data too. The way the data gets passed is when the child gets called from the parent, the child uses props.

In this example, the first bit of code is the parent and the second is the child. What is happening here is that the parent(app) is calling the child(videoList) and passing in the data in the call. The parent(app) passes the data by saying videos={window.exampleVideoData}. This gives the child(videoList) access to that data. Now inside the child(videoList), the word props is the data. In this case, the data is an array which is why in the child the map function can be called on props.videos. Props.videos is the same thing as calling exampleVideoData.videos. In summary, if the parent calls the child with the data, the child can just access the data using the word props.

Going from Child to Parent is a little bit trickier however.

Passing data from child to parent requires a callback function. Passing data from child to parent still uses props.

When data gets passed from the child to the parent, it does not directly pass from the child to the parent. Instead what happens is that the child creates a function(which gets called by the parent) that the manipulates the data in the parent, which then that data gets used by the parent and eventually makes it way back down to the child.

In this example, the child uses passes the data(dataToParent) using the callbackFromParent through props. This way the parent can use the data(dataToParent) in the callback function. It’s a little confusing.

First, a function is made inside the parent, this function will modify the data inside the parent using the data it gets from the child. Next, the parent calls the child and passes the function along to the child using the callbackFromParent as the key. Then, the child uses props to access the callbackFromParent and passes data as dataToParent back to the parent. Finally, the parent can use the dataToParent within its callback function.

In order to have access to the data from the child, all that needs to happen is that the this.state object needs to have a key of dataToParent and that way other functions can have access to the data from the child too. This is what line 9 does in the parent class.

Passing data in react can be a little bit difficult. But with practice, passing data will become relatively easy.