🎓 A1Learner
🔍
0 of 50 lessons completed

Controlled Inputs

A controlled input is an input whose value comes from state. React state holds the text, and the input shows it.

Value from state

The input shows the name state value.

const [name, setName] = useState('');
return <input value={name} onChange={(e) => setName(e.target.value)} />;

The state drives the text

The paragraph shows the same state value as the input.

const [name, setName] = useState('Ada');
return <p>Hello, {name}.</p>;

Example

import { useState } from 'react';

export default function App() {
  const [name, setName] = useState('');
  return (
    <div>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <p>Hello, {name}.</p>
    </div>
  );
}

Key points

  • The value attribute of the input reads the state value.
  • The onChange event runs when the text changes.
  • The handler stores the new text in state with the state setter.
  • State and input stay in step after every change.

In this example, the name state value starts empty. The input value reads the name state value. Each change calls the handler with the event. The handler stores the new text in state. The paragraph shows the same state value.

Note

An input with a value and no onChange cannot change.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What makes an input controlled?