TExcelTAD
Home › React › React Lists & Keys

React Lists & Keys

Most interfaces display collections: messages, products, search results, table rows. In React you turn an array of data into an array of elements with JavaScript's map() method, and you give each element a stable key.

Rendering a list with map

jsx · try it yourself
const planets = ['Mercury', 'Venus', 'Earth', 'Mars'];

export default function App() {
  return (
    <ul>
      {planets.map((planet) => (
        <li key={planet}>{planet}</li>
      ))}
    </ul>
  );
}

planets.map(...) returns an array of <li> elements, and React renders arrays by showing each item in order.

Lists of objects

Real data usually comes as objects with an id. Use that id as the key:

jsx · try it yourself
const books = [
  { id: 'b1', title: 'The Hobbit', author: 'J. R. R. Tolkien', year: 1937 },
  { id: 'b2', title: 'Dune', author: 'Frank Herbert', year: 1965 },
  { id: 'b3', title: 'Neuromancer', author: 'William Gibson', year: 1984 },
];

function BookRow({ book }) {
  return (
    <tr>
      <td>{book.title}</td>
      <td>{book.author}</td>
      <td>{book.year}</td>
    </tr>
  );
}

export default function App() {
  return (
    <table border="1" cellPadding="6" style={{ borderCollapse: 'collapse' }}>
      <thead>
        <tr><th>Title</th><th>Author</th><th>Year</th></tr>
      </thead>
      <tbody>
        {books.map((book) => <BookRow key={book.id} book={book} />)}
      </tbody>
    </table>
  );
}

The key goes on the outermost element returned by map — here <BookRow>, not the <tr> inside it.

Why keys matter

Keys tell React which item is which between renders. When the list changes (an item is inserted, deleted or reordered), React uses keys to match old and new elements, so each item keeps its own DOM node and state.

Try it: type something into each input below, then click Add to top. In the list keyed by index, your text stays in place while the labels move — the text ends up next to the wrong person. The list keyed by id stays correct.

jsx · try it yourself
import { useState } from 'react';

let nextId = 3;

function Row({ name }) {
  return (
    <li>
      {name}: <input placeholder={`note for ${name}`} />
    </li>
  );
}

export default function App() {
  const [people, setPeople] = useState([
    { id: 1, name: 'Ana' },
    { id: 2, name: 'Bao' },
  ]);

  function addToTop() {
    setPeople([{ id: nextId, name: `Guest ${nextId}` }, ...people]);
    nextId++;
  }

  return (
    <div style={{ display: 'flex', gap: 24 }}>
      <div>
        <h4>key = index ❌</h4>
        <ul>{people.map((p, i) => <Row key={i} name={p.name} />)}</ul>
      </div>
      <div>
        <h4>key = id ✅</h4>
        <ul>{people.map((p) => <Row key={p.id} name={p.name} />)}</ul>
      </div>
      <button onClick={addToTop} style={{ alignSelf: 'start' }}>Add to top</button>
    </div>
  );
}

Rules for keys

Rule Explanation
Unique among siblings Two items in the same list can't share a key; different lists can reuse keys
Stable The same item must get the same key on every render
Not random key={Math.random()} creates a new key each render and destroys state
Index only as a last resort Fine for static lists that never reorder, filter or insert
Not a prop The child can't read props.key; pass the id separately if needed

Filtering and sorting

Because map, filter and sort are just JavaScript, you can chain them. Copy before sorting ([...arr].sort() or toSorted()), since sort() mutates the array:

jsx · try it yourself
import { useState } from 'react';

const products = [
  { id: 1, name: 'Keyboard', price: 49, category: 'tech' },
  { id: 2, name: 'Mug', price: 9, category: 'home' },
  { id: 3, name: 'Headphones', price: 89, category: 'tech' },
  { id: 4, name: 'Lamp', price: 25, category: 'home' },
  { id: 5, name: 'Mouse', price: 19, category: 'tech' },
];

export default function App() {
  const [category, setCategory] = useState('all');
  const [cheapFirst, setCheapFirst] = useState(true);

  const visible = products
    .filter((p) => category === 'all' || p.category === category)
    .toSorted((a, b) => (cheapFirst ? a.price - b.price : b.price - a.price));

  return (
    <div>
      <select value={category} onChange={(e) => setCategory(e.target.value)}>
        <option value="all">All</option>
        <option value="tech">Tech</option>
        <option value="home">Home</option>
      </select>{' '}
      <button onClick={() => setCheapFirst(!cheapFirst)}>
        Sort: {cheapFirst ? 'cheapest first' : 'most expensive first'}
      </button>
      <ul>
        {visible.map((p) => (
          <li key={p.id}>{p.name} — ${p.price}</li>
        ))}
      </ul>
      <p>{visible.length} of {products.length} products</p>
    </div>
  );
}

Adding and removing items

Update list state by creating new arrays: spread to add, filter to remove, map to change one item.

jsx · try it yourself
import { useState } from 'react';

export default function App() {
  const [todos, setTodos] = useState([
    { id: 1, text: 'Water the plants', done: false },
    { id: 2, text: 'Read a chapter', done: true },
  ]);
  const [text, setText] = useState('');

  function add() {
    if (!text.trim()) return;
    setTodos([...todos, { id: Date.now(), text: text.trim(), done: false }]);
    setText('');
  }
  const toggle = (id) => setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
  const remove = (id) => setTodos(todos.filter((t) => t.id !== id));

  return (
    <div>
      <input value={text} onChange={(e) => setText(e.target.value)} placeholder="New task" />
      <button onClick={add}>Add</button>
      <ul>
        {todos.map((t) => (
          <li key={t.id}>
            <input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} />{' '}
            <span style={{ textDecoration: t.done ? 'line-through' : 'none' }}>{t.text}</span>{' '}
            <button onClick={() => remove(t.id)}>✕</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Tip: If an item has no natural id, generate one when the item is created (for example with crypto.randomUUID()), never during rendering.

Test yourself

Which array method is typically used to turn data into a list of elements?

  1. forEach
  2. map
  3. reduce
  4. push

Why is key={Math.random()} a bad idea?

  1. Keys must be strings
  2. The key changes every render, so React recreates items and loses their state
  3. Math.random is not allowed in JSX
  4. It's slower to type

Where does the key go when mapping to <Row /> components that each render a <tr>?

  1. On the <tr> inside Row
  2. On <Row key={…} />
  3. On the <tbody>
  4. Keys aren't needed for components