Iterate through a JavaScript Array with JSX and the `Array.map()` method

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson, we iterate through our JavaScript Array of names using the Array.map() method, so we can display each name on the screen.

Simon Vrachliotis: [0:00] We have an array of name objects in our App. Instead of just JSON.stringifying it, we want to display them in a nicely styled unordered list. Basically, we want to output a <ul> tag and then a series of <li> elements, one for each name. Each <li> should have a class of boy or girl to get the styling.

[0:19] We need to wrap each name in a button component, because we are going to allow users to click on each name. There. Looks pretty good now.

[0:28] How do we loop over each name and output an <li> element? When using a templating language, we sometimes have syntax like v-for in Vue.js, ng-for in Angular, or for name in names in Twig. JSX is not a templating language. It's just JavaScript. There are no templating helpers, but we have access to the full power of JavaScript.

[0:51] We have our names in an array. You can use the array .map method, for example, and for each entry in the array return a chunk of JSX.

[1:00] Let's return a list item with entry.name inside it. Just like that, we can see all our names listed on the page. If we open up the console, we can see that React is complaining about a missing unique key. We can use the entry.id for that and pass it in a key prop on the <li> element. Let's also add a className and set it to be entry.sex, which will be either boy or girl.

[1:26] Finally, let's wrap the entry.name inside a button and voilà. Our list of names is there and looking good.

egghead
egghead
~ 47 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