Course contentsShow
← React
Lesson 455 of 2,39613. Controlled ComponentsFree lesson

Controlled Text Inputs

Text inputs become controlled by setting value={state} and onChange={(e) => setState(e.target.value)}.

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:

  1. Store the input's value in state using useState
  2. Set the value prop on the input to that state variable
  3. Update state in an onChange handler using event.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 directly
  • onChange — When the user types, this handler fires on every keystroke
  • setUsername(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.