Lists & Keys

Render arrays with map() and give each item a stable key.

Syntax{items.map(item => <li key={item.id}>{item.text}</li>)}

To render a list, call .map() on an array and return a JSX element for each item. React needs a key on each element so it can track items across re-renders.

Choosing a key

  • Use a stable, unique id from your data whenever possible.
  • Avoid using the array index as a key if the list can reorder, insert or delete items.
  • Keys only need to be unique among siblings, not globally.

Example

Example Β· javascript
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>
          {todo.done ? 'βœ…' : '⬜'} {todo.text}
        </li>
      ))}
    </ul>
  );
}

When to use it

  • A task manager renders a dynamic to-do list using Array.map() and assigns each task's database ID as the key so React correctly diffs items when tasks are reordered.
  • A product catalogue maps over a paginated API response to render ProductCard components, using the product SKU as a stable key to avoid remounting on page change.
  • A chat application lists messages with keys derived from message IDs so React can append new messages without re-rendering the entire conversation history.

More examples

Simple list with map and key

Renders an array of items using map() and assigns each list item a stable unique key from the data.

Example Β· jsx
function FruitList({ fruits }) {
  return (
    <ul>
      {fruits.map(fruit => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}

Rendering component per item

Maps over a data array and renders a full child component for each item, keyed by its unique ID.

Example Β· jsx
function OrderList({ orders }) {
  return (
    <section>
      {orders.map(order => (
        <OrderCard
          key={order.id}
          orderId={order.id}
          total={order.total}
          status={order.status}
        />
      ))}
    </section>
  );
}

Filtering before rendering

Chains filter and map to render only the subset of items matching a condition before producing JSX.

Example Β· jsx
function ActiveUsers({ users }) {
  return (
    <ul>
      {users
        .filter(u => u.isActive)
        .map(u => (
          <li key={u.id}>
            {u.name} β€” {u.email}
          </li>
        ))}
    </ul>
  );
}

Discussion

  • Be the first to comment on this lesson.