Lesson 14 of 30
47%
Lists and Keys
To render a list, map an array to JSX.
Each item needs a key so React can match old rows to new rows when the list changes.
map
javascript
Why keys matter
Without keys, React uses the index. That breaks when you insert, delete, or sort.
A key should be stable and unique among siblings. An id from your data is perfect.
Do not use Math.random(). The key would change every render.
Index as key is a last resort
Only if the list never reorders and never inserts in the middle.
javascript
Extract a child component
When a row has more than one line of JSX, make a Row component. Put the key on the component in the map, not inside Row.
javascript
Empty lists
javascript
Tip: If a list glitches when you edit the first item, you probably used index as a key.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.