Sub topic 5
Adding to-dos with a controlled form
This chapter assumes you know useState, JSX, and basic event handlers, and that you have a Vite React project running. You will build the form that adds to-dos to the list.
What a controlled input is
A controlled input is a form field whose value lives in React state. The field shows what state says. Each keystroke calls a handler, the handler updates state, and React re-renders the field with the new value.
Two props make this work:
valuesets what the input displays.onChangeruns on every edit and receives the event.
If you set value without onChange, the field becomes read-only and React logs a warning.
The form
Use two pieces of state: todos for the list and text for the field's current contents. The form uses onSubmit, not a click handler on the button. That way the Enter key works too.
import { useState } from "react";
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("");
}
return (
<main>
<h1>To-do</h1>
<form onSubmit={addTodo}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</main>
);
}How the submit handler works
event.preventDefault()stops the browser from reloading the page, which is the default behavior of a form submit.text.trim()removes leading and trailing spaces. If nothing is left, the handler returns early, so blank to-dos never get added.[...todos, newTodo]builds a new array. React compares references, so a new array tells it to re-render. Callingtodos.push(...)would change the old array and the screen would not update.setText("")clears the field. Because the input is controlled, this also empties what the user sees.
The id comes from crypto.randomUUID(). It gives each item a stable identity, which the key prop uses in the list. Note that crypto.randomUUID() only works in secure contexts, meaning HTTPS or localhost.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Page reloads on submit | Missing `preventDefault()` | Call it first in the handler |
| Cannot type in the field | `value` set without `onChange` | Add an `onChange` that calls `setText` |
| New item does not appear | State was mutated with `push` | Create a new array with spread |
| Warning about uncontrolled to controlled | `value` started as `undefined` | Initialize state with `""` |
Try it
Run the app, type a task, and press Enter. Then submit an empty field and a field with only spaces. Neither should add an item.
Exercise
The Add button uses type="submit" and the form uses onSubmit. Why is this better than putting onClick on the button, and what happens if you remove event.preventDefault()?
Show answer
A form onSubmit handler runs for both the button click and the Enter key, so keyboard users get the same behavior. Without event.preventDefault(), the browser performs its default form submission and reloads the page. That wipes all React state, so the list and the input are reset.
Exercise
Change addTodo so it rejects a title that already exists in the list, ignoring upper and lower case. Which line do you add, and where?
Show answer
After computing title and the empty check, add if (todos.some((t) => t.title.toLowerCase() === title.toLowerCase())) return;. It runs before setTodos, so duplicates never reach state.