How do you render lists in React?

Experience Level: Junior
Tags: React

Answer

To render lists in React, we can use the map() method to iterate over an array of data and return an array of React elements. This allows us to dynamically generate list items based on the data we have. For example, let's say we have an array of names that we want to render as a list:


const names = ['John', 'Jane', 'Bob', 'Sally'];

const nameList = names.map((name) => {
  return <li>{name}</li>;
});

return (
  <ul>
    {nameList}
  </ul>
);

In this example, we use the map() method to iterate over the names array and return an array of <li> elements, each containing a name from the array. We then render this array of elements inside a <ul> element using curly braces to indicate that it is a JavaScript expression.

We can also add a unique key prop to each list item to help React identify each item and improve performance. For example:


const names = ['John', 'Jane', 'Bob', 'Sally'];

const nameList = names.map((name, index) => {
  return <li key={index}>{name}</li>;
});

return (
  <ul>
    {nameList}
  </ul>
);

In this example, we use the index parameter of the map() method as the key prop for each list item. While this is not ideal for performance, it is better than not having a key prop at all.

React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself