Forms & Controlled Inputs
Connect form inputs to state so React always knows their values — the “controlled component” pattern.
What you will learn
- Build controlled inputs with state
- Handle form submission
- Read all form values
Controlled inputs
A controlled input ties an input’s value to state and updates state onChange. React becomes the single source of truth for the value.
function App() {
const [email, setEmail] = useState("");
function handleSubmit(e) {
e.preventDefault();
alert("Submitting: " + email);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Your email"
/>
<button type="submit">Sign up</button>
<p>Preview: {email}</p>
</form>
);
}Here is the whole round-trip of a controlled form, step by step:
- State holds the value:
const [email, setEmail] = useState("")starts the email empty. - The input shows the state:
value={email}— the box always displays what is in state. - Typing updates the state:
onChange={(e) => setEmail(e.target.value)}runs on every keystroke and saves the new text. - React re-renders, so the live preview
{email}under the form updates instantly. - On submit,
handleSubmitruns.e.preventDefault()stops the browser from reloading the page, then we use the value (here, an alert).
Note: Output: An email box, a Sign up button, and a live Preview: line. Type in the box and the preview updates as you type. Click Sign up and an alert reads “Submitting: ” followed by what you typed.
Tip: The pattern is always the same: value={state} + onChange={e => setState(e.target.value)}. Once you know it for one input, you know it for all of them.
Note: Remember e.preventDefault() in the submit handler to stop the page reloading — just like in the JavaScript forms lesson.
Q. What makes an input “controlled” in React?
✍️ Practice
- Build a controlled text input and show its value live below it.
- Build a form with two fields that alerts both values on submit.
🏠 Homework
- Build a contact form (name, email, message) as controlled inputs that logs all values on submit.