Using Index as Key
0:00A developer built a todo list where users can add items at the top and delete any item. Users report strange behavior: when they delete an item, the wrong item's checkbox state seems to move around. When they add a new item at the top, the checkboxes get all mixed up.
0 flagged
javascriptclick lines to flag bugs
1
function TodoList() {2
const [todos, setTodos] = useState([3
{ id: 1, text: 'Learn React' },4
{ id: 2, text: 'Build app' },5
{ id: 3, text: 'Deploy' },6
]);7
8
const addTodo = (text) => {9
setTodos([{ id: Date.now(), text }, ...todos]);10
};11
12
const deleteTodo = (id) => {13
setTodos(todos.filter(t => t.id !== id));14
};15
16
return (17
<ul>18
{todos.map((todo, index) => (19
<li key={index}>20
<input type="checkbox" />21
<span>{todo.text}</span>22
<button onClick={() => deleteTodo(todo.id)}>23
Delete24
</button>25
</li>26
))}27
</ul>28
);29
}