Todo list
- React course
- Beginner
- Lesson 79/84
- 5 min
Render todos with map and toggle their done state.
Todo list
This lesson writes the TodoList component. We'll loop the todos array with .map and render each as <li key={ '{ todo.id }' }>...</li>.
The key prop is essential for React to match items in the list. Use a unique and stable value like id; avoid array index.
Next to each item we put a toggle button: it flips the done flag. This is done with setTodos and map.
Toggle logic
On toggle click, setTodos is called. With functional update, we map over each todo: the one with matching id has its done flag flipped.
The pattern: setTodos(prev => prev.map(t => t.id === id ? { '{ ...t, done: !t.done }' } : t)). Non-matching items stay the same; the matching one's done changes.
This is the spread + conditional pattern, the safest way to update one item in a list in React. Mutating the original array is forbidden.
Practice Write TodoList
Complete the skeleton. Write a TodoList component. Take ({ '{ todos, onToggle }' }) as parameter. Inside <ul>, use todos.map(todo => ...) to render each todo as <li key={ '{ todo.id }' }> with <span>{ '{ todo.text }' }</span> and <button onClick={ '{ () => onToggle(todo.id) }' }>Toggle</button>. Export it.
Starter code
// Write the TodoList component hereSample solution
function TodoList({ todos, onToggle }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<span>{todo.text}</span>
<button onClick={() => onToggle(todo.id)}>Toggle</button>
</li>
))}
</ul>
);
}
export default TodoList;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 List key
Each item in a list needs a ____ prop.
Each item in a list needs a key prop.
Explanation: Each item gets a key prop.
2 What's the best value for key?
- Unique id Correct answer
- Array index
- Random number
- Item text
Explanation: A unique id is the best key.
3 Match the list steps
| Term | Meaning |
|---|---|
map |
Iterates |
key={id} |
Unique |
toggle |
flip done |
spread |
Copy + change |