Sub topic 11
Rendering lists and choosing keys
This chapter assumes you can write function components, pass props, embed expressions in JSX with curly braces, and use map and filter on arrays.
Turning an array into elements
JSX can hold an array of elements inside curly braces. React renders each element in order. To build that array from data, call map and return one element per item.
function TodoList({ todos }) {
if (todos.length === 0) {
return <p>Nothing to do.</p>;
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
export default function App() {
const todos = [
{ id: 'a1', text: 'Write chapter' },
{ id: 'b2', text: 'Review chapter' },
];
return <TodoList todos={todos} />;
}The early return handles the empty case. The map call handles every other case. To show a subset, chain filter before map: todos.filter((t) => !t.done).map(...).
What a key does
A key is a string or number that identifies an item among its siblings. On each render, React compares the new list with the previous one and uses keys to decide which items are the same. A matched item keeps its DOM node and its state. An item with a new key is created. An item whose key disappeared is removed.
Without keys, React warns in the console and falls back to matching by position.
Choosing good keys
A good key is unique among siblings and does not change for the same item.
- Prefer an id that comes with the data, such as a database primary key.
- If items have no id, create one when the item is created, for example with
crypto.randomUUID(). Do not create it during render. - Use the array index only for a list that is never reordered, filtered, or edited in the middle.
- Never use
Math.random(). A new key on every render makes React discard and rebuild every item.
Index keys fail quietly. Say a list has three rows, each containing a text input, and you delete the first row. With index keys, the rows now have keys 0 and 1, so React keeps the first two DOM nodes and removes the last. The remaining data shifts up, but the text a user typed stays in the old nodes. Input text ends up beside the wrong item. With stable ids, React removes the correct node.
Where the key goes
Put the key on the outermost element returned inside map, not on an element nested inside it. If each item needs a fragment, the short <> syntax cannot take a key. Import Fragment and write it out.
import { Fragment } from 'react';
function Glossary({ terms }) {
return (
<dl>
{terms.map((term) => (
<Fragment key={term.id}>
<dt>{term.name}</dt>
<dd>{term.meaning}</dd>
</Fragment>
))}
</dl>
);
}When you extract the item into its own component, the key stays on the component in the map call, as in <TodoItem key={todo.id} todo={todo} />. It does not go inside TodoItem.
Common errors
| Symptom | Likely cause |
|---|---|
| Console warning about missing keys | `map` returns elements with no `key` |
| Warning about duplicate keys | Two items share an id, or a field is not unique |
| Typed text or focus jumps to the wrong row | Index keys on a list that changes order or length |
| Items lose their state on every render | Keys are generated during render |
| Key set but still warned | Key is on an inner element, not the outermost one |
Exercise
A list of users is sorted by name, and each row has a checkbox. The code uses key={index}. After the user changes the sort order, the checked boxes stay in the same positions instead of following their users. Why does this happen, and what is the fix?
Show answer
With index keys, the key belongs to the position, not to the user. After sorting, React matches each new row to the old DOM node at the same position, so the checkbox state stays at that position while the user data changes. Use a stable, unique value from the data, such as key={user.id}, so React moves each row with its user.