Keys in Lists
Keys in lists are short labels that help React track each item in a list. A key stays with its item when the list changes.
A key on each item
The id of each fruit is its key.
{fruits.map((fruit) => <li key={fruit.id}>{fruit.name}</li>)}Ids in the data
Each fruit carries its own id.
const fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
];The list on the page
Keys never show in the rendered page.
<ul>
{fruits.map((fruit) => <li key={fruit.id}>{fruit.name}</li>)}
</ul>Example
export default function App() {
const fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' },
];
return (
<ul>
{fruits.map((fruit) => <li key={fruit.id}>{fruit.name}</li>)}
</ul>
);
}
Key points
- A key is a short label on a list item.
- Each key must differ from the other keys in the list.
- An id from the data makes a good key.
- React uses the key to match each item after a change.
In this example, three fruits sit in the array, each with its own id. The map method builds one list item for each fruit. Each item carries its id as its key. The page shows a list with three items. The keys never show in the page.
Note
A key never shows in the rendered page.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What should each key be in a list?