Pass data down to children component with props in React

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

egghead
egghead
~ 33 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today