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

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.