Sub topic 4
Rendering rows from an array, and why keys matter
What this chapter assumes
You should know how to write a function component, read props, and use JSX expressions in curly braces. You should also know the array methods map and forEach. This chapter covers how React turns an array into elements and what the key attribute does. The searchable product table uses these ideas in the next chapter.
From an array to elements
JSX can render an array of elements. React places each element in the array as a sibling, in order. So you can turn data into UI by building an array of elements from your data.
The map method is the usual way to do this:
function NameList({ names }) {
return (
<ul>
{names.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
);
}map returns a new array with one <li> per name. React renders it inside the <ul>.
The product table builds its rows differently. It needs a category heading before the first product of each category. That is hard to express with map, so it uses a loop that pushes into an array:
const rows = [];
let lastCategory = null;
products.forEach((product) => {
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}
/>
);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});Both approaches give React an array of elements. forEach is the better fit when one data item can produce zero, one, or two elements. A product that is not stocked might be skipped later, and a new category produces an extra heading row.
What a key is
A key is a special attribute on an element in an array. React uses it to match each element in the new render to an element in the previous render.
Without keys, React could only compare siblings by position. With keys, React can tell that the element with key Apple is the same element as before, even if it moved. This matters because React preserves the state and the DOM node of an element that it matches. If React matches the wrong elements, a row's state ends up attached to the wrong data.
The matching works like this:
Choosing a key
A good key identifies one data item, and it stays the same across renders. Keys only need to be unique among siblings in the same array. Two different lists can reuse the same keys.
| Source of key | When to use it | Problem |
|---|---|---|
| Database ID or other stable ID | Data comes from a server or has an ID field | None, this is the best choice |
| A unique field such as `name` | The field is unique and does not change | Breaks if two items share the value, or if the field is editable |
| Array index | The list is static: never reordered, filtered, inserted into, or removed from | State sticks to positions instead of items |
| `Math.random()` or `crypto.randomUUID()` during render | Never | A new key every render makes React remount every row |
The product data has no ID field. The tutorial uses product.name as the key for products and product.category for category rows. That works because each name appears once in the sample data. In a real application you would add an id field to each product and use it.
Generate IDs when you create the data, not while rendering. If you assign an ID when the user adds an item, the ID stays with the item for its whole life.
What goes wrong with index keys
Index keys are the most common source of confusing list bugs. This component stores a note in each row's own 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 Demo() {
const [names, setNames] = useState(['Apple', 'Dragonfruit', 'Peas']);
return (
<div>
<button onClick={() => setNames(names.slice(1))}>Remove first</button>
<ul>
{names.map((name, index) => (
<Row key={index} label={name} />
))}
</ul>
</div>
);
}Run it and follow these steps:
- Type
ripein the input next to Apple. - Click "Remove first".
Apple disappears, but ripe now sits next to Dragonfruit. The array shrank from three items to two. With index keys, React sees keys 0 and 1 in the new render and matches them to keys 0 and 1 from before. The row with key 0 keeps its state, and only its label prop changes. Key 2 is gone, so React removes the last row.
Change key={index} to key={name} and the bug disappears. React now sees that the Apple key is missing and removes that row with its state.
Keys in the product table
The product table has an extra detail: category rows and product rows go into the same array. React compares keys among all siblings, so a category key and a product key must not collide.
In the sample data, the categories are Fruits and Vegetables, and the product names are different words. No collision occurs. But suppose a category and a product both had the name Apple. Two siblings would share the key Apple, and React would warn and might misbehave. Prefix the keys to avoid this:
rows.push(
<ProductCategoryRow
category={product.category}
key={`category-${product.category}`}
/>
);
rows.push(<ProductRow product={product} key={`product-${product.name}`} />);You can use the unprefixed keys from the sample while you are sure the values are distinct. If the data comes from outside your control, prefix them.
Keys also stay correct after the filtering you add later in the tutorial. Filtering removes rows from the array. The rows that remain keep their keys, so React matches them to the same rows as before. If you had used indexes, filtering would shift every key after the first removed row.
Where to put the key
The key goes on the outermost element that you put into the array. It does not go on something nested inside it.
This is wrong, because the array contains <ProductRow> elements without keys:
products.map((product) => (
<ProductRow product={product}>
<td key={product.name}>{product.name}</td>
</ProductRow>
));This is right:
products.map((product) => (
<ProductRow product={product} key={product.name} />
));Two more points about where keys go.
- Keys are not props. React reads
keyitself and does not pass it to your component. IfProductRowneeds the name, pass it as a separate prop such asname. - Fragments need the long form. The short fragment syntax
<>...</>cannot take a key. When one data item produces several elements and you want one array entry, importFragmentand write<Fragment key={...}>:
import { Fragment } from 'react';
function Group({ category, products }) {
return (
<Fragment key={category}>
<tr>
<th colSpan="2">{category}</th>
</tr>
{products.map((p) => (
<tr key={p.name}>
<td>{p.name}</td>
<td>{p.price}</td>
</tr>
))}
</Fragment>
);
}In this version the key on Fragment inside Group does nothing, because the key belongs on the element in the parent's array. When you render <Group> from a parent, put key={category} on <Group> itself. The point of the example is the Fragment import. Use Fragment with a key when the fragment is the element you place directly in an array.
Common errors
- "Each child in a list should have a unique key prop." An element in an array has no key. Add one to the outermost element in the array.
- The same key warning with duplicates. Two siblings share a key. Check for duplicate data or for category and product values that collide.
- State jumps to the wrong row. The list uses index keys and then changes order or length. Switch to a stable ID.
- Inputs lose focus on every keystroke. The key changes on each render, often because of
Math.random(). Make the key stable. - A key that includes mutable data. If you build the key from a field the user can edit, such as a product name in an editable table, each edit changes the key. React then remounts the row. Use an ID that does not change.
Summary of the rules
- Render an array by building an array of elements with
map, or with a loop that pushes. - Give every element in the array a key.
- Keys must be unique among siblings, and stable across renders.
- Prefer a real ID. Use the index only for lists that never change.
- Put the key on the outermost element in the array.
Exercise
A list of todo items is rendered with todos.map((todo, index) => <TodoItem key={index} todo={todo} />). Each TodoItem has a checkbox with its own state (not controlled by the parent). The user checks the second item, then deletes the first item. Which item now appears checked, and how do you fix it?
Show answer
The item that was third now appears checked in the second position... no: the checked state belongs to key 1. After deleting the first item, the old second item moves to key 0 and the old third item moves to key 1. React keeps the state for key 1, so the old third item appears checked. The fix is to give each todo a stable ID when you create it and use key={todo.id}. React then matches state to the item instead of the position.
Exercise
In the product table, a data change adds a product named Fruits under the category Vegetables. Why is this a problem, and what is one way to prevent it?
Show answer
The category row for Fruits and the product row named Fruits are siblings in the same rows array, and both would use the key Fruits. Duplicate keys cause a warning and can make React reuse or drop the wrong row. Prefix the keys, for example category-Fruits and product-Fruits, or give each product a unique id and use it.