Sub topic 7
Controlled inputs with onChange
This chapter assumes you know JavaScript arrow functions, basic JSX, components and props, and the useState hook. It also assumes you can attach a handler such as onClick and read the event object.
What "controlled" means
A controlled input is a form field whose value lives in React state. The input shows whatever the state holds. When the user types, an onChange handler copies the new text into state, and React re-renders the input with that value.
You make an input controlled by setting two props together:
valuesets what the field displays.onChangeruns on every edit and updates the state.
import { useState } from 'react';
function NameField() {
const [name, setName] = useState('');
return (
<label>
Name
<input value={name} onChange={e => setName(e.target.value)} />
<p>Hello, {name || 'stranger'}</p>
</label>
);
}e.target is the input element that fired the event, and e.target.value is its current text. React's onChange fires on every keystroke, unlike the browser's native change event, which fires when the field loses focus.
Why the state is the source of truth
Because the input displays value from state, the state is the single source of truth. You can read it at any time, validate it, or transform it before it reaches the screen.
import { useState } from 'react';
function CodeField() {
const [code, setCode] = useState('');
function handleChange(e) {
setCode(e.target.value.toUpperCase().slice(0, 6));
}
return <input value={code} onChange={handleChange} />;
}This field forces uppercase and caps the length at six characters. The user cannot enter anything that the handler rejects, because the displayed text is always the state.
Other field types
Not every field uses e.target.value. Checkboxes use checked, and selects use value.
import { useState } from 'react';
function Preferences() {
const [subscribed, setSubscribed] = useState(false);
const [plan, setPlan] = useState('free');
return (
<div>
<label>
<input
type="checkbox"
checked={subscribed}
onChange={e => setSubscribed(e.target.checked)}
/>
Email me updates
</label>
<select value={plan} onChange={e => setPlan(e.target.value)}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</div>
);
}Several fields, one handler
A form with many fields can share one handler by giving each input a name and using it as the key to update an object in state.
import { useState } from 'react';
function ProfileForm() {
const [form, setForm] = useState({ first: '', last: '' });
function handleChange(e) {
const { name, value } = e.target;
setForm(f => ({ ...f, [name]: value }));
}
return (
<div>
<input name="first" value={form.first} onChange={handleChange} />
<input name="last" value={form.last} onChange={handleChange} />
</div>
);
}The [name] syntax is a computed property key. The spread ...f copies the other fields so they are not lost.
Common errors
- A
valuewithoutonChange. The field becomes read-only, and React warns in the console. AddonChange, or usereadOnlyif that is intended. - Switching from uncontrolled to controlled. If the state starts as
undefined, React treats the input as uncontrolled, then warns when a value arrives. Initialize with'', notundefined. - Mutating an object in state. Writing
form[name] = valuedoes not trigger a re-render. Create a new object, as in the example above. - Reading the event inside a delayed callback. Copy
e.target.valueinto a variable first if you use it later, for exampleconst { value } = e.target;.
Exercise
Why does this input not let the user type anything, and how do you fix it? const [text, setText] = useState(''); return <input value={text} />;
Show answer
The input is controlled by value, but nothing updates text, so the displayed value never changes. Add onChange={e => setText(e.target.value)} so each keystroke updates the state.
Exercise
In the ProfileForm example, what would go wrong if the handler were setForm({ [name]: value })?
Show answer
It would replace the whole state object with one key, so the other field's value would be lost (and become undefined). Spreading the previous state with ...f keeps the other fields.