Lists and keys
You'll learn to turn an array of data into a list on screen with map, and why each item needs a key.
map, and a wrong key causes strange bugs.Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Watch map turn each object into a list item with a key.
Explanation
Your to-do app keeps tasks in an array of objects. You want one line on screen per task. You don't write
the lines by hand: you map the array into JSX, and React shows the array of elements it gets back.
<ul>{tasks.map((task) => (<li key={task.id}>{task.title}</li>))}</ul>
Each task becomes one <li>. The key is a name tag for each item. When the list changes (a task is
added, deleted or moved), React uses the keys to know which item is which, so it updates the right
line and keeps things like a ticked checkbox with the right task.
A good key is unique in that list and never changes for the same item. An id from your data is
best. The position in the array (the index) changes when you delete or reorder, so avoid it when the list
can change. Never use Math.random(): it gives a new key on every render.
If you forget the key, the list still shows, but the console warns: Each child in a list should have a unique "key" prop. Treat that warning as a bug.
People often add { } to the arrow and forget return. Then the arrow returns undefined for every
item, and the list is empty with no error. Use ( ) after the =>, or write return.
When you read a map in JSX, ask: what does one item become, and what is its key?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const students = [2 { id: 1, name: "Rafi" },3 { id: 2, name: "Nusrat" },4];56function ClassList() {7 return (8 <ul>9 {students.map((s) => {10 <li key={s.id}>{s.name}</li>;11 })}12 </ul>13 );14}
addTask gives each new task an id to use as its key. After a task is deleted, it can hand out an id that is already taken. Fix it so a new id is always one more than the biggest id in the list.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3Which is the best key for a task in a to-do list?
- 2 / 3Where does the
keygo? - 3 / 3What does
{tasks.map((t) => { <li key={t.id}>{t.title}</li> })}show?
Explain it back
How confident are you with Lists and keys?
Done
map inside JSX, say what list appears, and spot a missing or unstable key.