0 day streak
javascript / beginner
Snippet

Controlled Text Inputs

In React, input state should be handled by the component. We link the input's value to a state variable and update it whenever the user types.

snippet.js
javascript
1
2
3
4
5
6
7
const [name, setName] = useState('');
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
react
Breakdown
1
value={name}
Forces the input to display the current value from the React state.
2
e.target.value
Accesses the current string typed into the input field from the event object.