Sub topic 5
Adding to-dos with a controlled form
This chapter assumes you can write function components, call useState, and attach event handlers such as onClick. It also assumes you are comfortable with array spread syntax and basic HTML forms. By the end, you will have a form that adds new to-dos to a list held in state.
What "controlled" means
An HTML input normally keeps its own value inside the browser's DOM. You read it only when you need it. A controlled input reverses this. React state holds the value, and the input displays whatever the state says.
Two props make an input controlled:
valuesets what the input shows.onChangeruns on every edit, so you can copy the new text into state.
The cycle looks like this:
- The user presses a key.
- The browser fires a change event.
- Your
onChangehandler callssetTextwith the new text. - React re-renders, and the input receives the new
value.
The input never changes on its own. Each character appears only because your state changed first. This costs a few lines of code, and you get one source of truth. You can clear the field, validate it, or transform it by changing state alone.
The complete form
This is the full App component for this chapter. It holds two pieces of state: the list of to-dos and the text currently typed into the field.
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>
);
}Replace the contents of src/App.jsx in your Vite project with this and run npm run dev. Type a task and press Enter or click Add. The task appears in the list and the field empties.
How the pieces work
Two state variables with different jobs
todos is the application data. text is a draft that exists only while the user types. Keeping the draft in its own state means typing causes re-renders but never touches the list.
The change handler
<input value={text} onChange={(e) => setText(e.target.value)} />e.target is the input element, and e.target.value is its current text. The handler passes that text to setText. React calls onChange on every keystroke, unlike the native DOM change event, which fires only when the field loses focus.
The submit handler
Put the logic on the form's onSubmit, not on the button's onClick. A browser submits a form when the user clicks a submit button or presses Enter in a text field. Only onSubmit catches both. If you used onClick, pressing Enter would do nothing, which is a quiet accessibility failure.
Inside addTodo, four things happen in order:
event.preventDefault()stops the browser's default behavior, which is to reload the page and send the form data to the current URL. A reload would wipe all your state.text.trim()removes leading and trailing spaces.if (!title) return;rejects empty or whitespace-only input. An empty string is falsy, so this guard covers both.setTodos([...todos, newTodo])builds a new array containing the old items plus the new one, andsetText("")clears the draft.
The new to-do object
Each to-do is a plain object with three fields: id, title, and done. The id comes from crypto.randomUUID(), which returns a unique string. Later chapters use this id as the list key and to find items when toggling or deleting. crypto.randomUUID() works only in secure contexts, meaning HTTPS or localhost. On a plain http:// address over a network, it is undefined and your handler throws.
Why the new array matters
[...todos, newTodo] creates a fresh array. React decides whether state changed by comparing references. If you call todos.push(newTodo) and then setTodos(todos), the reference is the same, so React may skip the update, and the list will not appear. Always pass a new array to the setter. The next chapters build on this when toggling and deleting.
A safer update form
The handler above reads todos from the render in which the handler was created. That works for one submit per render. If you ever add several items in one event, each call sees the same old todos and later ones overwrite earlier ones. Pass an updater function to avoid this:
setTodos((current) => [
...current,
{ id: crypto.randomUUID(), title, done: false },
]);React calls the function with the latest queued state. Use this form whenever the new state depends on the previous state. It becomes more important once updates come from timers or effects.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Input will not accept typing, and the console warns about `value` without `onChange` | `value` is set but there is no handler, so React treats the field as read-only | Add `onChange` that calls the setter |
| Warning about changing an uncontrolled input to controlled | The state started as `undefined`, for example `useState()` | Initialize with `""` |
| Page reloads on submit and the list vanishes | `preventDefault()` is missing | Call it first in the handler |
| Enter does not add an item | The logic is on the button's `onClick` | Move it to the form's `onSubmit` |
| Blank items appear | No guard after trimming | Check `if (!title) return;` |
| New item does not show up | State was mutated with `push` | Pass a new array to the setter |
| Handler throws `crypto.randomUUID is not a function` | The page is served over plain HTTP from a non-localhost address | Use HTTPS or `localhost` |
Edge cases worth deciding on
- Duplicates. The code allows two to-dos with the same title. That is fine because ids differ. If you want to block duplicates, compare lowercased titles before adding.
- Whitespace inside the title.
trim()only removes the ends. "Buy milk" keeps its inner spaces. - Focus after submit. The input keeps focus after you press Enter, so the user can type the next task. If they clicked the button, focus moves to the button. Returning focus to the input is a refinement you can add with a ref.
- Validation feedback. Silently ignoring an empty submit is simple but gives the user no hint. An error message held in a third piece of state is the usual next step.
The label
The input sits inside a <label>, which gives it an accessible name, "New task". Clicking the label text focuses the input, and screen readers announce the name when the field gets focus. A placeholder alone is not a substitute, because it disappears as soon as the user types. The test in a later chapter finds this input by its label, so this markup does double duty.
Exercise
A learner writes <input value={text} /> and <button onClick={addTodo}>Add</button> (no form element). They report two problems: they cannot type in the field, and pressing Enter does nothing. Explain the cause of each problem and give the minimal fix.
Show answer
The field is read-only because value is set without an onChange handler, so React keeps showing the state value no matter what the user types. Add onChange={(e) => setText(e.target.value)}. Pressing Enter does nothing because there is no <form>, so the browser has nothing to submit, and only the button's click is wired up. Wrap the input and button in <form onSubmit={addTodo}>, make the button type="submit", drop its onClick, and call event.preventDefault() at the start of addTodo.
Exercise
Modify addTodo so it rejects a title that matches an existing to-do, ignoring letter case. What should the check look like?
Show answer
After computing title, add if (todos.some((t) => t.title.toLowerCase() === title.toLowerCase())) return; before calling setTodos. some returns true as soon as one item matches, so the function exits without changing state, and the draft text stays in the field.