Controlled Inputs

What this is. A controlled input is one where React state holds the value and the input displays it. One source of truth.

That is what makes it possible to validate as someone types, clear the field after submitting, or fill it in from elsewhere.

The pairing. value and onChange go together. value alone makes the field read-only and React will warn you. onChange alone means the input keeps its own value and your state never learns about it.

Start the state as an empty string rather than undefined, or the input begins uncontrolled and switches later, which produces a warning that confuses everyone the first time.

Try it

Add a button that clears the field. With controlled state that is one line: setEmail('').

loading editor…

loading React…

The message is derived during the render rather than stored, so it can never disagree with the field.

Submitting. Handle onSubmit on the form rather than onClick on the button. The form's submit event fires when someone presses Enter in a field, which a click handler never sees, and plenty of people submit forms that way.

Call e.preventDefault() first, or the browser reloads the page and everything in state is gone.

◈ Graded Component

Build a search form. It needs a form containing an input with id q and a submit button. Typing into the input must update state. Submitting the form must display the submitted text inside an element with id result, reading Searching for: TEXT. Before anything is submitted, that element must read Nothing searched yet. Submitting must not reload the page.

Checked against what your component renders and how it responds, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back