Text Input: value and onChange
What you'll learn: How to connect a text input to React state so the component controls what appears in the field.
The Core Pattern
A controlled text input in React requires two props working together:
value={state}— tells the input what text to displayonChange={(e) => setState(e.target.value)}— updates state when the user types
This creates a loop: state flows into the input via value, user changes trigger onChange, which updates state, causing a re-render that updates the input's value again.
The Code
const [name, setName] = useState('');
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
How It Works Step-by-Step
- User types a character
- Browser triggers the
onChangeevent - Your handler extracts
e.target.value(the input's new text content) - You call
setName(e.target.value), scheduling a state update - React re-renders, passing the new
namevalue back to the input - The input displays the updated text
The Event Object
The e parameter is React's synthetic event. Inside onChange, e.target refers to the actual input element, and e.target.value is its current string content.
Why Both Props Are Required
Without value, the input is uncontrolled (DOM manages its state). Without onChange, the input becomes frozen (user can't type because state never updates). Together, they give React complete control.
Key Takeaway: A controlled text input needs both value={state} to display current state and onChange={(e) => setState(e.target.value)} to update it when the user types—creating the foundation for form handling in React.