React Foundations · State

Controlled inputs

Controlled inputs

You type into a box, then need that text somewhere else on the page — a live preview, a search filter, a character count. The typed value lives inside the DOM, where React cannot read it.

A controlled input fixes this: React state holds the value, and the input reports every change back through onChange. State becomes the single source of truth for what the box shows.

const [text, setText] = useState('');

<input value={text} onChange={(event) => setText(event.target.value)} />;

Two things make it controlled:

  • value={text} — the input always displays the current state.
  • onChange — every keystroke calls the setter with the input's new value.

Because the value comes from state, you can read it anywhere in the component — for example, to render a live preview beside the input. An uncontrolled input keeps its own value in the DOM, so React cannot see it.

Your job is to control an input and mirror its text in a paragraph. The component lives in App.jsx.

Challenge

Typing into the input leaves the paragraph beside it blank. Export an App component from App.jsx that renders a text input controlled by state and a paragraph showing the current text.

The Test types hi into the input and expects the paragraph to read hi. The starter's input is uncontrolled, so the paragraph never changes and the Test fails.

App.jsx
export function App() {
  return (
    <div>
      <input />
      <p />
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.