React ยท Chapter 11 of 42

Controlled Inputs

A controlled input is one whose value is driven by React state, rather than by the DOM itself. You set `value={state}` and update state via `onChange`.

Controlled inputs make it easy to validate, transform, or react to input as the user types.

Setting up a controlled input

Bind the input's `value` to a state variable, and update that state in the `onChange` handler using `event.target.value`.

Why use them?

Controlled inputs let you enforce formatting, disable submit buttons until valid, and keep a single source of truth in state.

Example 1 (jsx)
import { useState } from "react";

function NameInput() {
  const [name, setName] = useState("");
  return (
    <input
      value={name}
      onChange={(e) => setName(e.target.value)}
    />
  );
}
Output
(input reflects state as you type)

Every keystroke updates state, which re-renders the input's value.

Key points

  • Controlled inputs have their value driven by React state.
  • Use onChange with event.target.value to update state.
  • They provide a single source of truth for form data.
  • Useful for validation and conditional UI based on input.
๐Ÿ’ก Note: Forgetting the onChange handler on a controlled input makes it read-only, and React will warn you.

๐Ÿ“ Quick Quiz

1. What drives a controlled input's value?

2. Which event updates state as the user types?

3. How do you read the typed value in onChange?