Course contentsShow
← React
Lesson 481 of 2,39613. Controlled ComponentsFree lesson

Text Input: value and onChange

Implement controlled text inputs with value={state} and onChange={(e) => setState(e.target.value)}.

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:

  1. value={state} — tells the input what text to display
  2. onChange={(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

  1. User types a character
  2. Browser triggers the onChange event
  3. Your handler extracts e.target.value (the input's new text content)
  4. You call setName(e.target.value), scheduling a state update
  5. React re-renders, passing the new name value back to the input
  6. 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.