Pass data down to children component with props in React

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, we import our list of names - a JavaScript Array - in our index.js file. We then pass it to the App component as a "prop", so it becomes possible for children components to access that data.

Simon Vrachliotis: [0:00] Let's import our list of names in our app's entry point. Import { names } from './data'. The way we can pass data to children components is via props. Here in my app component, I can add a names prop, which will be equal to names.

[0:18] Names here is imported from this file here and corresponds to an array of objects, each with an id, a sex, and a name property. We are passing this names array to our App component, so now we can go and receive it in the App component.

[0:35] In App.js, let's accept props as a parameter. To see what's available in there, let's output a <pre> tag, and in there, open curlies to write some JavaScript and do JSON.stringify(props). We'll also pass null and 2, to have a nicely formatted output.

[0:53] You can see that we have a props object with our names array here. This is named names because this is how we called it to the prop pass-down in our index.js file.

[1:03] If we rename the prop hello in there, this is how it will be named. Let's rename it to names, and instead of receiving all the props here, we'll destructure the names out of it. Now if I change my JSON.stringify to names, we can see we get just the names array. Nice. This is just what we want.

[1:24] To recap, we are importing a names named export at the root of our App which corresponds to an array of names in this file. We then pass these names down to our App component through a names prop. We receive that prop in the App component and are able to print it out on the screen.