Sub topic 11
Controlled inputs
This chapter covers how to make a form field read its value from state and write changes back to state. It assumes you can write function components, use useState, handle events, and use spread syntax. It also assumes you know the earlier chapters on object state, since the multi-field form reuses that pattern.
What "controlled" means
A controlled input is a form element whose displayed value comes from React state instead of from the browser's own internal storage. You pass the state to the element through the value prop (or checked for checkboxes). You pass an onChange handler that copies the user's edit into state.
The data flows in a loop:
- The user types a character.
- The browser fires a change event.
- Your
onChangehandler calls the state setter with the new text. - React re-renders, and the input receives the new
value.
The state is the single source of truth. The DOM element only shows what state says.
A single text field
import { useState } from 'react';
function NameField() {
const [name, setName] = useState('');
return (
<>
<label>
Name
<input value={name} onChange={e => setName(e.target.value)} />
</label>
<p>Hello, {name || 'stranger'}.</p>
</>
);
}e.target is the input element, and e.target.value is the text it holds after the edit. Because the paragraph reads name from state, it updates on every keystroke with no extra code.
Why the field freezes without onChange
If you set value but give no onChange, the field becomes read-only. Each keystroke changes the DOM text, but React re-renders nothing new, so the value snaps back to what state says. React also logs a warning in development. Two fixes exist:
- Add an
onChangehandler, which makes the field controlled. - Use
defaultValueinstead ofvalue, which makes the field uncontrolled. The browser then owns the text, and React only sets the starting value.
If a field should be read-only on purpose, add the readOnly attribute to silence the warning.
Many fields in one object
The ProfileForm pattern from the object-state chapter uses one handler for every field. It relies on each input's name attribute matching a key in the state object.
import { useState } from 'react';
function ProfileForm() {
const [person, setPerson] = useState({ name: '', email: '' });
function handleChange(e) {
setPerson({ ...person, [e.target.name]: e.target.value });
}
return (
<form>
<input name="name" value={person.name} onChange={handleChange} />
<input name="email" value={person.email} onChange={handleChange} />
</form>
);
}The bracket syntax [e.target.name] is a computed property key. When the user edits the email field, it evaluates to email, so the new object keeps name from the spread and replaces only email. The handler builds a new object each time, so React sees a changed state value.
If two quick updates could overlap, prefer an updater function so the second update starts from the first one's result:
function handleChange(e) {
const { name, value } = e.target;
setPerson(prev => ({ ...prev, [name]: value }));
}Destructuring name and value before calling the setter also matters in practice. The updater runs later, and reading e.target inside it works in current React, but copying the values first keeps the code clear and safe in any version.
Other input types
Not every input uses value and e.target.value. The table shows the prop pair for each common element.
| Element | State prop | Read from event | Typical state type |
|---|---|---|---|
| `<input type="text">`, `email`, `password` | `value` | `e.target.value` | string |
| `<textarea>` | `value` | `e.target.value` | string |
| `<input type="checkbox">` | `checked` | `e.target.checked` | boolean |
| `<input type="radio">` | `checked` on each option | `e.target.value` | string |
| `<select>` | `value` on the `select` | `e.target.value` | string |
| `<input type="number">` | `value` | `e.target.value` | string |
Three details cause most of the bugs here.
- A
<textarea>takesvalueas a prop. In HTML you put the text between the tags, but in React you do not. - A
<select>takesvalueon the<select>element itself, notselectedon each<option>. - A number input still gives you a string. Convert it with
Number(e.target.value)when you need arithmetic.
Here is a form that mixes several types:
import { useState } from 'react';
function Preferences() {
const [form, setForm] = useState({
nickname: '',
plan: 'free',
newsletter: false,
});
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm(prev => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
}
return (
<form>
<input name="nickname" value={form.nickname} onChange={handleChange} />
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
<label>
<input
type="checkbox"
name="newsletter"
checked={form.newsletter}
onChange={handleChange}
/>
Send me the newsletter
</label>
<p>{JSON.stringify(form)}</p>
</form>
);
}The handler checks type to decide whether to read checked or value. Without that check, a checkbox would store the string "on" instead of a boolean.
Submitting the form
A form's submit event reloads the page by default. Call e.preventDefault() in the onSubmit handler, then read the values from state. You do not need to read the DOM.
import { useState } from 'react';
function SignUp() {
const [email, setEmail] = useState('');
const [submitted, setSubmitted] = useState(null);
function handleSubmit(e) {
e.preventDefault();
setSubmitted(email.trim());
setEmail('');
}
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={e => setEmail(e.target.value)} />
<button type="submit">Join</button>
{submitted && <p>Thanks, {submitted}.</p>}
</form>
);
}Clearing a field is just setEmail(''). This is a main benefit of control: you can reset, prefill, or transform values from code.
Transforming input as it is typed
Because every edit passes through your handler, you can change the value before storing it. This example keeps only digits:
import { useState } from 'react';
function PhoneField() {
const [phone, setPhone] = useState('');
return (
<input
value={phone}
onChange={e => setPhone(e.target.value.replace(/\D/g, ''))}
inputMode="numeric"
/>
);
}Typing a letter makes the handler store the same digits as before. React re-renders with an unchanged value, and the letter disappears. Keep these transforms simple. Aggressive rewriting, such as inserting dashes as the user types, can move the cursor to the end of the field and annoy people who edit in the middle of the text.
Derived values and validation
Do not store anything you can compute from the input. Validation messages and character counts belong in the render body, as the derived-values chapter showed.
import { useState } from 'react';
function Bio() {
const [bio, setBio] = useState('');
const limit = 80;
const remaining = limit - bio.length;
return (
<>
<textarea value={bio} onChange={e => setBio(e.target.value)} />
<p style={{ color: remaining < 0 ? 'crimson' : 'inherit' }}>
{remaining} characters left
</p>
</>
);
}Common errors
- Value is
undefinedat first. Starting state asundefinedornullmakes the input uncontrolled, and React warns when it later becomes controlled. Start text state as''. - Mutating the state object. Writing
person[e.target.name] = e.target.valueand then callingsetPerson(person)passes the same object, so React may skip the re-render. Always create a new object. - Mismatched
name. If an input'snamedoes not match a state key, the handler adds a stray key and the real field never updates. - Reading state right after the setter. Inside a handler,
namestill holds the old snapshot aftersetName(...). Use the event value if you need the new text immediately. - Defining the component inside another component. React sees a new component type on each render and remounts the input, so it loses focus after every keystroke. Define components at the top level of the module.
Exercises
Exercise
A text input has value={title} but no onChange and no readOnly. What happens when the user types, and what are two ways to fix it?
Show answer
The field cannot be edited: React re-renders with the unchanged title, so the text snaps back, and development builds log a warning. Fix it by adding an onChange handler that calls the setter with e.target.value, or by switching to defaultValue to make the input uncontrolled. Adding readOnly is correct only if the field should not be edited.
Exercise
A form stores { subscribed: false } and uses one shared handleChange that always saves e.target.value. After the user ticks the checkbox, subscribed is the string "on". How do you fix the handler?
Show answer
Read checked for checkboxes. Destructure type, value, and checked from e.target, then store type === 'checkbox' ? checked : value. Give the checkbox the prop checked={form.subscribed} so the input stays controlled.