Sub topic 11
Controlled inputs
This chapter assumes you know useState, event handlers, and spread syntax. It also assumes you have seen state snapshots and immutable object updates.
What "controlled" means
A controlled input is a form element whose displayed value comes from React state. The browser does not keep its own copy. You pass value to the input and update the state in onChange. State is then the single source of truth.
One handler for several fields
Keep related fields in one object. Give each input a name that matches its key, then use a computed property name in the handler.
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 spread copies the old fields into a new object. [e.target.name] then overwrites only the field that changed. React sees a new object and re-renders.
Other input types
Not every input uses value. Checkboxes use checked and e.target.checked. Radio buttons use checked on each option. A <select> and a <textarea> both take value, as a text input does.
<input
type="checkbox"
checked={subscribed}
onChange={e => setSubscribed(e.target.checked)}
/>Common errors
valuewithoutonChange. React warns, and the field becomes read-only because state never changes. Add a handler, or usereadOnlyon purpose.- Initial
undefinedornull. Starting withundefinedmakes the input uncontrolled. When state later becomes a string, React warns about switching modes. Start with''. - Mutating state. Writing
person.name = e.target.valuedoes not trigger a re-render. Always pass a new object to the setter. - Reading state right after the setter. The handler sees the snapshot from its own render. Use
e.target.valuewhen you need the new value inside the same handler.
When to prefer a controlled input
Use a controlled input when you need to validate as the user types, disable a button based on content, format input, or reset the form from code. For a simple form that you read once on submit, an uncontrolled input is enough.
Exercise
A text input has value={query} and no onChange, so the user cannot type in it. Why does this happen, and how do you fix it?
Show answer
React renders the input from query, which never changes, so every keystroke is discarded and the field appears frozen. Add onChange={e => setQuery(e.target.value)} so the handler updates state and React re-renders with the new value.