Sub topic 11
Rendering lists and choosing keys
This chapter assumes you can write function components, embed expressions in JSX with curly braces, pass props, and use useState. You should also know Array.prototype.map and filter. Here you will turn arrays of data into lists of elements and learn how React uses keys to decide which item is which.
Mapping data to elements
JSX has no loop syntax. Instead, you use a JavaScript expression that produces an array of elements. React renders each element in the array in order. The expression is usually map:
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>
);
}Three details matter in this example:
- The arrow function passed to
mapuses parentheses around the JSX, so it returns the element implicitly. If you use curly braces for the function body, you must writereturn. A missingreturngives an array ofundefinedvalues, which renders nothing and produces no error. - The early
returnhandles the empty list. Without it,<ul>would render with no children. - Each
<li>has akeyprop.
What keys are for
When state changes, React calls your component again and compares the new element tree with the previous one. This comparison is called reconciliation. For a list, React must work out which new item corresponds to which old item. The correspondence matters because each item can own state (for example, text typed into an input) and DOM nodes (focus, scroll position, selection).
Without keys, React can only match items by position. With keys, React matches items by identity: the item with key "a" in the new render is the same item that had key "a" in the last render, wherever it now sits.
Because the diagram fence below must follow the required format, here it is in full:
Rules for keys
A good key meets these conditions:
- Unique among siblings. Keys only need to be unique within one array, not across the whole app. Two different lists can use the same ids.
- Stable. An item keeps the same key across renders. The same data item must always produce the same key.
- Derived from the data. An id from a database, a UUID created when the item was added, or another natural unique value all work.
Keys are not passed to your component. Inside TodoItem, props.key is undefined. If the child needs the id, pass it under another name, such as id={todo.id}.
Where the key goes
The key belongs on the outermost element returned inside map. If you extract a component, put the key on the component tag at the call site, not inside the component:
function TodoItem({ text }) {
return <li>{text}</li>;
}
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} text={todo.text} />
))}
</ul>
);
}The short fragment syntax <>...</> cannot take attributes. When each item returns several siblings, import Fragment and write the long form:
import { Fragment } from 'react';
function Glossary({ terms }) {
return (
<dl>
{terms.map((term) => (
<Fragment key={term.id}>
<dt>{term.word}</dt>
<dd>{term.meaning}</dd>
</Fragment>
))}
</dl>
);
}Why index keys cause bugs
Many tutorials write key={index} to silence the warning. The warning goes away, but the underlying problem remains. If the list can be reordered, filtered, or have items inserted or removed, an index no longer identifies an item. It identifies a position.
This component shows the bug. Each row keeps its own note in state:
import { useState } from 'react';
function Row({ label }) {
const [note, setNote] = useState('');
return (
<li>
{label}:{' '}
<input value={note} onChange={(e) => setNote(e.target.value)} />
</li>
);
}
export default function App() {
const [items, setItems] = useState([
{ id: 'a', label: 'Apples' },
{ id: 'b', label: 'Bananas' },
{ id: 'c', label: 'Cherries' },
]);
return (
<>
<button onClick={() => setItems(items.slice(1))}>Remove first</button>
<ul>
{items.map((item, index) => (
<Row key={index} label={item.label} />
))}
</ul>
</>
);
}Type "fresh" into the Apples row, then click "Remove first". The label of the first row changes to Bananas, but the input still says "fresh". React saw key 0 in both renders, so it kept that row's state and only updated its label prop. The last row (key 2) was the one React removed.
Change the key to key={item.id} and the behavior is correct. React sees that key "a" is gone, removes that row with its state, and keeps rows "b" and "c" as they were.
Index keys are acceptable when all of these hold: the list is built from static data, it is never reordered or filtered, and its items have no state. If you are unsure, use an id.
Generating ids
Keys must come from the data, so assign ids when you create the data, not when you render it.
import { useState } from 'react';
export default function TodoApp() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');
function addTodo() {
if (text.trim() === '') return;
setTodos([...todos, { id: crypto.randomUUID(), text }]);
setText('');
}
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</>
);
}crypto.randomUUID() runs once, inside the event handler. Calling it inside map, as in key={crypto.randomUUID()} or key={Math.random()}, creates a new key on every render. React then treats every item as new, destroys and recreates every row, and the inputs lose focus and state on each keystroke.
Note that crypto.randomUUID() is available in secure contexts (HTTPS and localhost). In other environments, use a counter or an id from your backend.
Filtering, sorting, and derived lists
You can chain array methods before map. Keep the original array in state and derive the visible list during render:
function VisibleTodos({ todos, showDone }) {
const visible = showDone ? todos : todos.filter((todo) => !todo.done);
const sorted = [...visible].sort((a, b) => a.text.localeCompare(b.text));
return (
<ul>
{sorted.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}sort mutates the array it is called on. Calling it directly on a prop would change the parent's data during render, which breaks the purity rule you will see in a later chapter. Copy first with [...visible] or use toSorted where your runtime supports it. filter and map already return new arrays.
Keys stay attached to the data, so a filtered or sorted list keeps each item's state with that item.
Keys outside lists
A key can also reset a component. If you change the key on a single component, React treats it as a different component and mounts a fresh one, discarding the old state:
<ProfileForm key={userId} userId={userId} />When userId changes, the form starts empty instead of carrying over the previous user's draft. This is often simpler than writing an effect that clears state.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Console warning "Each child in a list should have a unique key" | No `key` on the outermost element in `map` | Add `key={item.id}` |
| Key placed on the `<li>` inside `TodoItem` instead of on `<TodoItem>` | The key must be on the element returned from `map` | Move the key to the call site |
| Input text jumps to the wrong row after removing or reordering | `key={index}` | Use a stable id |
| Inputs lose focus on every keystroke | `Math.random()` or `crypto.randomUUID()` called during render | Create ids once, when data is created |
| Nothing renders from `map` | Arrow function with braces and no `return` | Add `return` or use parentheses |
| Two rows share state or one is missing | Duplicate keys among siblings | Make keys unique |
| `[object Object]` appears in the page | Rendering an object directly | Render one of its fields |
Summary
Use map to turn data into elements, and give each result a key that is unique among its siblings, stable across renders, and taken from the data. Put the key on the outermost element returned by map. Avoid index keys for lists that change, and never generate keys during render.
Exercise
A list of Row components uses key={index}. Each Row holds an input with its own state. A user types in the second row, then another item is inserted at the top of the list. Describe what the user sees and give the fix.
Show answer
React matches rows by index. The typed text stays in the slot at index 1, but that slot now shows the item that was previously first, so the text appears next to the wrong item. Give each data item a stable id when it is created and use key={item.id}. React then moves the existing row with its state to its new position and mounts a new row for the inserted item.
Exercise
What is wrong with this code, and what happens at runtime? {products.map((p) => <ProductCard product={p} />)} where the ProductCard component renders <li key={product.id}>...</li>.
Show answer
The key is on the wrong element. The array elements returned by map are <ProductCard> elements, and they have no key, so React warns that each child needs a unique key. The inner key on the <li> does not identify the ProductCard items. Write <ProductCard key={p.id} product={p} /> and remove the key from the <li>.
Exercise
Why is [...visible].sort(...) used instead of visible.sort(...) in the VisibleTodos example?
Show answer
sort changes the array in place. If visible is the same array as the todos prop, sorting it during render changes data owned by the parent. Copying the array first leaves the prop untouched, so the component stays pure.