Introduction
Forms are how users give an app information: signing up, searching, adding an item. In React, the usual approach is to keep each field's value in state, so the component always knows what the user has typed and can react to it at once: show a preview, enable a button, explain a mistake. Such fields are called controlled inputs.
How it works
A controlled input takes its value from state and updates the state in onChange:
const [name, setName] = useState("");
<input value={name} onChange={(e) => setName(e.target.value)} />
Every keystroke fires onChange (in React, unlike in plain HTML, it fires on each change, not when the field loses focus), the setter stores the new text, and React renders the input with it. Because the state is the single source of the value, the component can use it anywhere: in a preview, in a validation message, or to clear the field by setting it to "".
Other fields work the same way with a different property. A checkbox uses checked and reads e.target.checked. A select uses value on the select element itself, and the option whose value matches is selected. A textarea uses value too.
The form's submit event is handled once for the whole form, with onSubmit on the form element: call event.preventDefault(), then validate the values in state and either use them or show what is wrong. Validation can also run live during render, for example disabling the submit button until the email contains an @.
Some values should not be state at all. A greeting built from the name, a total built from a price and a quantity, or the number of characters typed are all derived values: compute them during render. Storing them in state as well means keeping two things in step by hand, which eventually goes wrong.
You can also leave a field uncontrolled, with defaultValue, and read it from the form on submit, as in the events lesson. Controlled inputs are the better choice when the component needs the value before submit.
Example
Line by line
- Three fields, three state variables: the name text, the chosen plan and whether the terms are accepted.
- The text input and the select use
value; the checkbox useschecked. - The preview line is derived from
nameduring render, with "stranger" when it is empty. handleSubmitstops the reload, checks the fields in order and sets a message.- The message is shown only when there is one, using
&&with a string, which is safe because an empty string renders nothing.
Expected result
The preview first says "Hello, stranger". Typing Ada changes it to "Hello, Ada" at once. Submitting without ticking the box shows "Please accept the terms."; after ticking it and choosing Pro, submitting shows "Welcome, Ada! You chose the pro plan."
In the real world
Sign-up forms, checkout pages, settings screens and search boxes are built from controlled inputs. Large forms often use a form library that manages the state, validation and error messages, but underneath it does what this lesson does. Showing errors next to the field as the user types, rather than only after submitting, is one of the most effective improvements to a form's usability.
Common mistakes
- Setting value without onChange, which makes the input impossible to type in.
- Reading e.target.value for a checkbox, which is always "on"; read
e.target.checked. - Storing derived values in state, such as both a price and the total it implies.
- Forgetting preventDefault in onSubmit, which reloads the page.
Best practices
- Connect every input to a label, by wrapping it or with
htmlFor. - Validate on submit and, where it helps, as the user types; say exactly what is wrong.
- Keep form state minimal and derive the rest during render.
Summary
Controlled inputs keep a field's value in state, with value (or checked for checkboxes) from state and onChange updating it on every change. Forms are handled once with onSubmit and preventDefault, values are validated before use, and anything that can be computed from the state is computed during render rather than stored.
Quick check
Key takeaways
- A controlled input gets value from state and calls the setter in onChange; checkboxes use checked.
- Validate in onSubmit (after preventDefault) or live during render, and show clear messages.
- Compute what you can from state during render instead of storing it twice.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.