Skip to the workspace
Pebellslearn by building
Rendering  ›  Lesson

Lists and Keys

Lists and Keys 15 minReact turns an array into a list of elements with map, and each element needs a key that is stable and unique among its siblings so React can track it.

react / Lists and Keys

Explore each scene at your own pace.

01 · The rule

The rule

Lists and Keys

A reading list is, well, a list. You will not write <BookCard /> by hand for every book; you have an array, and you want one card per item. JavaScript's map does that. React then asks for one extra thing you must not ignore.

The rule

Map the array; key each item by who it is, not where it is.

Map the array. map turns each piece of data into a piece of JSX, and React renders an array of elements in order:

const books = [
  { id: 'b1', title: 'The Hobbit', author: 'J. R. R. Tolkien' },
  { id: 'b2', title: 'Dune', author: 'Frank Herbert' },
  { id: 'b3', title: 'Emma', author: 'Jane Austen' },
];

function BookList() {
  return (
    <ul>
      {books.map(book => (
        <li key={book.id}>{book.title} — {book.author}</li>
      ))}
    </ul>
  );
}

To show only some items, filter first and then map: books.filter(b => !b.read).map(...).

Key each item by who it is. A key is how React recognises an item from one render to the next. When the list changes, React matches old and new items by key, then keeps, moves, adds or removes elements accordingly — along with any state inside them.

The key rules:

  • Unique among siblings. Two lists elsewhere may reuse the same keys.
  • Stable. The same item keeps the same key forever. Ids from your data are ideal.
  • On the outermost element returned from map. If you return a fragment, use <Fragment key={book.id}>, since the <> shorthand cannot take a key.
  • Not a prop. BookCard cannot read key; pass id separately if it needs it.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.