DevPath · Learn to code ESPTEN

Lists and conditional rendering

Render lists with .map() and key

From an array to a list of elements

Almost any real interface shows collections: a list of tasks, the results of a search, the comments on a post. In React there is no special loop inside JSX: you use the .map() method of arrays to transform each piece of data into a JSX element.

function ShoppingList() {
  const products = ["Bread", "Milk", "Eggs"];
  return (
    <ul>
      {products.map((product) => (
        <li>{product}</li>
      ))}
    </ul>
  );
}

.map() returns a new array, this time of <li> elements, and React knows how to paint an array of elements one after another. Notice that the .map() goes inside curly braces { }: it is a JavaScript expression embedded in the JSX.

The key prop

If you run the code above, React will show a warning in the console:

Warning: Each child in a list should have a unique "key" prop.

Each element of a list needs a special prop called key: a unique and stable identifier within that list.

<ul>
  {products.map((product) => (
    <li key={product}>{product}</li>
  ))}
</ul>

What is the key for?

The key helps React identify each element across renders. When the list changes (an element is added, removed, or reordered), React compares the keys to know which element is which and update only what is needed, instead of recreating the whole list. This improves performance and avoids subtle bugs (for example, the text of an <input> jumping to another row).

A good key:

What about the .map() index?

.map() gives you the index as a second argument:

{products.map((product, index) => (
  <li key={index}>{product}</li>
))}

Using the index as key is tempting, but it is fragile: if the list is reordered, filtered, or elements are inserted/removed in the middle, the index of each piece of data changes, and React can confuse the rows. It is only acceptable when the list is static (does not change order or size) and you do not have a better id.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Conditional rendering →