javascript / beginner
Snippet
Managing Form Inputs with the Controlled Component Pattern
The controlled component pattern stores form field values directly inside React component state. Instead of letting the DOM maintain its own internal input value, the value attribute is bound to a state variable and updated synchronously on every keystroke via the onChange event handler.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { useState } from 'react';export function UsernameInput() {const [username, setUsername] = useState('');return (<inputtype="text"value={username}onChange={(e) => setUsername(e.target.value)}placeholder="Enter username"/>);}
react
Breakdown
1
const [username, setUsername] = useState('');
Declares a string state variable initialized to an empty string to hold the input value.
2
value={username}
Binds the displayed text of the input element directly to the current state value.
3
onChange={(e) => setUsername(e.target.value)}
Captures the input change event and updates the string state with the newly typed text.