Sub topic 4
Rendering rows from an array, and why keys matter
This chapter assumes you can write a function component, use JSX, and call array methods such as map and forEach. It covers how React turns an array into rows and what the key prop does.
Turning data into elements
JSX can hold an array of elements. React renders each element in order. So to show a list, build an array of elements from your data and place it inside {}.
const products = [
{ name: 'Apple', price: '$1' },
{ name: 'Spinach', price: '$2' }
];
function SimpleTable() {
const rows = products.map((product) => (
<tr key={product.name}>
<td>{product.name}</td>
<td>{product.price}</td>
</tr>
));
return (
<table>
<tbody>{rows}</tbody>
</table>
);
}The product table in this tutorial needs more than a plain map. Rows must be grouped under category headings, so the table walks the sorted array with forEach and pushes elements into a rows array.
function ProductTable({ products }) {
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;
});
return (
<table>
<tbody>{rows}</tbody>
</table>
);
}lastCategory remembers the previous product's category. A heading row is added only when the category changes works because the data is already sorted by category.
What a key is
A key is a string or number that identifies one item among its siblings. React uses keys to match the elements from the previous render with the elements from the next one.
Without keys, React can only compare items by position. When the list changes, that causes two kinds of problems:
- React may reuse the wrong DOM node or component state. An input in row 2 can end up showing the text typed into a different row.
- React may do extra work. It updates many rows instead of inserting or removing one.
With keys, React sees that "Peas" is still "Peas" even when it moves, appears, or disappears.
Choosing a good key
A good key is unique among siblings and stays the same for the same item across renders.
| Key source | Verdict | Reason |
|---|---|---|
| Database ID | Best | Stable and unique by design |
| Unique field such as `name` | Fine here | Works if values never repeat in the list |
| Array index | Risky | Changes when items are reordered, inserted, or removed |
| `Math.random()` | Wrong | A new key on every render forces React to recreate every row |
The mockup data has no ID, so the tutorial uses product.name for products and product.category for headings. This is acceptable for a fixed example. In a real app, add an ID to your data.
Common errors
- Missing key warning. React logs "Each child in a list should have a unique key". Add
keyto the element at the top level of the loop. - Key on the wrong element. The key belongs on the outermost element you create in the loop, not on something inside it. In
ProductRow, the key is set where<ProductRow />is created, not on the<tr>inside the component. - Expecting to read
key. React does not passkeyto the component. If a child needs the value, pass it as a separate prop. - Duplicate keys. Two siblings with the same key cause rows to be skipped or duplicated. Here, the category headings and products share one
rowsarray. A product named "Fruits" would collide with the "Fruits" heading. In a larger dataset, prefix keys, for example `cat-${category}`.
Exercise
A teammate renders rows with key={index} from products.map((product, index) => ...). The list can be sorted, and each row will later contain a text input. What bug can this cause, and what is a better key?
Show answer
After sorting, each index points to a different product. React then matches rows by position, so the text typed into an input can stay in the same position while the product moves. Use a stable unique value from the data, such as a product ID, or product.name if names are unique.