What is a controlled form input in React?
Short answer
A controlled input gets its current value from React state and updates that state every time the user types, using the onChange event. This means React always knows exactly what the input currently shows, making it easy to validate or transform the value at any moment.
Advertisement
AModel answer
A controlled input gets its current value from React state and updates that state every time the user types, using the onChange event. This means React always knows exactly what the input currently shows, making it easy to validate or transform the value at any moment.
function NameInput() {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}Real-world example
A signup form keeps track of a user's chosen username in state as they type, letting the app instantly check and show whether that username is already taken, without waiting for the user to submit the form first.
Likely follow-ups
- What happens if you provide a value prop to an input without also giving it an onChange handler?
- How do you clear a controlled input's value programmatically?
Related topics