Controlled Text Inputs
What you'll learn: How to make a text input fully controlled by binding its value to React state with value and onChange.
The Core Pattern
A controlled text input is an <input> element whose value is explicitly managed by React state. You control it by doing three things:
- Store the input's value in state using
useState - Set the
valueprop on the input to that state variable - Update state in an
onChangehandler usingevent.target.value
Here's the complete pattern:
function LoginForm() {
const [username, setUsername] = useState('');
return (
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
);
}
Why All Three Parts Matter
value={username}— The input always displays what's in state, not what the user typed directlyonChange— When the user types, this handler fires on every keystrokesetUsername(e.target.value)— You capture the new input value and update state, which triggers a re-render with the new value
Think of it like a feedback loop: user types → onChange fires → state updates → component re-renders → input displays new state value.
What Makes It "Controlled"
The input has no opinion about its own value. React state is the single source of truth. The input can only display what state tells it to. This gives you complete control: you can transform, validate, or reject input changes before they appear.
Key Takeaway: Controlled text inputs use the pattern value={state} + onChange={(e) => setState(e.target.value)} to make React state the authoritative source of the input's value, giving you full programmatic control over what appears in the field.