Keys
React shows a list, and then the data changes: a band is added at the start, another one cancels, the list gets sorted. React then doesn't draw the whole list again. It compares the new list with the one on the page and changes only what's different. For that, it has to know which item is which: is the second item still the same band as before, or a new one?
That's what the key is for: a name for each item, which React recognizes it by. You give it in the attribute key of the element that map() returns:
const stages = [
{ id: 1, name: "Main Stage" },
{ id: 2, name: "Tent" },
{ id: 3, name: "Forest Stage" },
];
export default function App() {
return (
<ul>
{stages.map((stage) => (
<li key={stage.id}>{stage.name}</li>
))}
</ul>
);
}With the key, React knows that the item with the key 3 is the Forest Stage, wherever it is in the list. And the warning from the previous exercise is gone.
Rules for keys:
- A key must be unique among the items of one list. (Two different lists can use the same keys.)
- It must stay the same for the same item. Take it from the data: usually, that's its
id. That's one of the reasons why data from servers and databases has ids. When the items are texts that never repeat, the text itself can be the key:key={name}. - The key isn't shown on the page, and it isn't one of the props: a component can't read it.
Why not the position in the array? map() gives its function the position as a second argument, and key={index} makes the warning go away too. But when a band is added at the start, every other band moves one position further and gets a new key. React then thinks the first item is still the one it knew, and it mixes the items up. You'll see what that does once the items remember something of their own (in the State lesson): one band's likes would end up with another band. Keys from ids don't change when the order does.
Instructions
Give each li a key: the band's id. Run the code: the warning is gone from the console.
Show the time before each name, as in 20:00 Night Trains.