Rendering Lists — React

A list in React is made with array.map(). Its callback (the function you give to map) returns one element for each item in the array, and React shows that…

A WhatsApp chat list, the menu in a food delivery app, the items in a shopping cart: almost every app shows a list. The data arrives as an array, and how many items it holds can change at any time. So you don't write each <li> by hand. You turn that array into a set of elements, one element for each item in the array. You do it with map, the array method you already know from JavaScript.

It's like printing wedding invitations: you only need one design, the guest list is the long part, and the printer uses the same design for every name. In React, the design is the JSX for one item, the guest list is the array, and the printer is map.

From an array to <li>

This code makes one <li> for every fruit in the fruits array:

function App() {
  const fruits = ["Apple", "Mango", "Orange"];

  return (
    <ul>
      {fruits.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

This is what happens on each turn of map (one turn for each fruit):

Turn item What the callback returns
1 "Apple" <li key="Apple">Apple</li>
2 "Mango" <li key="Mango">Mango</li>
3 "Orange" <li key="Orange">Orange</li>

map returns an array holding 3 <li> elements. React can show an array: it shows the items one by one, in order. The result in the browser:

<ul>
  <li>Apple</li>
  <li>Mango</li>
  <li>Orange</li>
</ul>

If you add one fruit to the array, a fourth <li> appears by itself. The JSX doesn't change at all.

One small slip can leave the list empty. If the callback uses curly braces, (item) => { <li>{item}</li> }, nothing is returned because there's no return. The result of map becomes [undefined, undefined, undefined], and React shows nothing for undefined. So 0 <li> elements appear, with no error. Use plain parentheses, or write return <li>{item}</li>; inside the curly braces.

key: a name tag for every item

Every element map makes needs a key prop: a value that tells that item apart from the other items in the same list. When the data changes, React runs the component again (a re-render). Then React matches old items to new items by their key. Without a key, React writes a warning in the console: Each child in a list should have a unique "key" prop.

Data from a database almost always has an id, and that id is the best key. A list of texts that are all different, like the fruit names in the first example, can use the text itself.

What about index, the item's position in the array ((item, index) => <li key={index}>)? index is a place in line, not the item's identity. When an item is inserted at the top, removed, or the order changes, the items' places shift, and React can match the wrong items. So index isn't ideal as a key. It's only safe for a list whose order never changes. Why React can match the wrong items is covered in full in the next lesson, Keys & Reconciliation.

A list from an array of objects

Real data is usually objects. Read each property with a dot, and use the id as the key:

function App() {
  const fruits = [
    { id: 1, name: "Apple", price: 1.2 },
    { id: 2, name: "Mango", price: 1.5 },
    { id: 3, name: "Orange", price: 0.8 },
  ];

  return (
    <ul>
      {fruits.map((b) => (
        <li key={b.id}>
          {b.name}: {b.price.toLocaleString("en-US", { style: "currency", currency: "USD" })}
        </li>
      ))}
    </ul>
  );
}

The result is three rows: Apple: $1.20, Mango: $1.50, Orange: $0.80.

If you only want to show some of them, use filter first, then map:

{fruits
  .filter((b) => b.price < 1)
  .map((b) => <li key={b.id}>{b.name}</li>)}

Only Orange costs less than $1, so only one <li> is made.

⚠️ Why is the list empty, or not updating?

TL;DR: A list in React is made with array.map(). Its callback (the function you give to map) returns one element for each item in the array, and React shows that array of elements in order. Every element needs a key, a name tag that's unique in the list and stays the same for the same item. Ideally the key is the id from the data, put on the element map returns (not on the <ul>). index (the item's position in the array) as a key isn't ideal when the list's order can change. A callback with { } needs return. Without it, the list is empty. Using forEach instead of map shows nothing. Only need some items? filter first, then map.

⚡ map: one item, one element

Write:

function App() {
  const fruits = ["Apple", "Mango", "Orange"];

  return (
    <ul>
      {fruits.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

Meaning: fruits.map(...) runs the callback (the function inside the brackets of map) for every fruit, then collects the results into an array of <li> elements. React shows that array in order. If you add one fruit, a fourth <li> appears by itself. key={item} is the name tag of each <li>.

⚡ Curly braces need return

Guess first: how many <li> elements does fruits.map((item) => { <li>{item}</li> }) make?

Zero, with no error. There's no return, so map gives [undefined, undefined, undefined]. Use plain parentheses, or write return.

Meaning: A callback with curly braces needs return. forEach shows nothing either, because it returns nothing. To make JSX from an array, always use map.

⚡ key: a name tag for every item

Guess first: index is the item's position in the array (0, 1, 2 and so on). Is key={index} a good choice?

Not ideal when the list's order can change. When the list changes, React matches old items to new items by their key. index is a place in line, not an identity: when the order changes, the same item gets a different index, so React can match the wrong items.

Meaning: A key must be unique in one list and stable for the same item. Put it on the element map returns. Ideally the key is the id from the data, such as key={b.id}, where b holds one fruit object that has an id.

What you will learn