0 day streak
javascript / beginner
Snippet

Controlled Inputs (Two-Way Binding)

A controlled component has its value driven by React state. The 'value' prop sets the current text, and 'onChange' updates the state whenever the user types, keeping the UI and state in sync.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function NameForm() {
const [name, setName] = useState('');
return (
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}
react
Breakdown
1
value={name}
Links the input's displayed value to the 'name' state variable.
2
onChange={(e) => setName(e.target.value)}
An event handler that captures the user input from the event object and updates the state.