Sub topic 2
Adding To-Dos with a Controlled Form
Assume you know JavaScript functions, arrays, objects, map, filter, and basic HTML forms. You also need a React project created with Vite or a similar tool.
Adding to-dos with a controlled form
A controlled input is a form field whose value comes from React state. The onChange handler updates that state whenever the user types. The submit handler then validates the text, creates a to-do, and stores a new array.
import { useState } from "react";
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span>{todo.title}</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}
export default function App() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState("");
function addTodo(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
setTodos([
...todos,
{ id: crypto.randomUUID(), title, done: false },
]);
setText("");
}
function toggleTodo(id) {
setTodos(todos.map((todo) =>
todo.id === id ? { ...todo, done: !todo.done } : todo
));
}
function deleteTodo(id) {
setTodos(todos.filter((todo) => todo.id !== id));
}
return (
<main>
<h1>To-do list</h1>
<form onSubmit={addTodo}>
<label>
New task
<input
value={text}
onChange={(event) => setText(event.target.value)}
/>
</label>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={toggleTodo}
onDelete={deleteTodo}
/>
))}
</ul>
</main>
);
}Rendering lists with stable keys
React uses a key to match each list item with its previous render. Use an ID that stays with the item. Do not use the array index when items can be deleted or reordered.
Updating state without mutation
State mutation changes an existing array or object directly. Avoid it because React may not detect the change reliably. map creates a new array and the spread syntax creates a changed object. filter creates a new array without the deleted item.
Lifting state up to `App`
When several components need the same data, keep that data in their nearest shared parent. This pattern is called lifting state up. App owns todos; TodoItem only displays one item and reports user actions through callbacks.
Exercise
Why should a to-do key use todo.id instead of the array index?
Show answer
The ID remains attached to the same to-do when items are deleted or reordered, so React can preserve the correct item state.