Controlled input
- React course
- Beginner
- Lesson 49/84
- 4 min
Learn to write a controlled component by binding input value to state.
Controlled input
Making an input controlled means binding its value to state. You give the input's value attribute the state and its onChange the updater.
Form: <input value={text} onChange={e => setText(e.target.value)} />. The input always shows the state; each keystroke updates the state.
This is the heart of the React form approach: a single source of truth, the state.
The onChange flow
On each keystroke onChange fires, the handler reads e.target.value and updates state with setText. React re-renders; the input shows the new value.
This loop is very fast; the user feels smooth typing. This is React's "one-way data flow".
Without a controlled input React does not know the content; so we always use controlled inputs.
Practice Controlled input
Complete the skeleton. Write a NameInput component; import useState. Define const [text, setText] = useState("");. Return <input value={text} onChange={e => setText(e.target.value)} />. Export it.
Starter code
import { useState } from "react";
// Define NameInput hereSample solution
import { useState } from "react";
function NameInput() {
const [text, setText] = useState("");
return <input value={text} onChange={e => setText(e.target.value)} />;
}
export default NameInput;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does a controlled input's value come from?
State is the single source of truth.- From browser memory
- From the DOM
- From state Correct answer
- Not from props
Explanation: value={text} makes state the source.
2 Controlled input: fill in the missing part
<input value={text} onChange={e => setText(e.____)} />
<input value={text} onChange={e => setText(e.target.value)} />
Explanation: e.target.value gives the current text.
3 Controlled input: match the terms
| Term | Meaning |
|---|---|
value |
State source |
onChange |
Change event |
e.target.value |
Current text |
setText |
Updater |