Display a List in React by Looping Over an Array of Items

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

To display a list of items in react, we can map (or loop) over that list and return JSX from inside the map function:

    <div>
      {
        props.items.map(item => {
          return <p key={item.id}>{item.title}</p>
        })
      }
    </div>

Remember to always include a key attribute though! That lets React keep track of each list item internally, which gives you better performance, and may save you from subtle bugs

Chris Achard: [0:00] Let's say we have some data here and we want to display that in a list on the web browser. First, let's make a new function component. We'll call that function component MyList for now. That will take props because what we're going to do is render the list down here. We can render it, and we're going to pass the data as props.

[0:19] We might say items = the JavaScript value, DATA. Now this props will have props.items, which will be the data array. We did that mostly for practice in passing props.

[0:34] From MyList, we're going to return JSX. Let's make a <div> wrapper. To loop over this data, we're going to use curly braces to run JavaScript, and we're going to call props.items -- so we have access to the array -- .map(). Map takes a function which will return each item in a loop. From there, we want to return just a paragraph with the title. Inside of here we can say item.title.

[1:04] We're almost done, but on every iteration of the loop we're going to also want to set a key. The key is React specific and lets React keep track of which paragraph tag goes to which row in the data. It means you'll get better performance. We're going to set that to item.id because id is unique across all of these.

[1:22] If we save this now, we get our three list items displayed with our map function.

egghead
egghead
~ an hour 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