Preparing your workspace
A controlled input gets its current value from React state and reports user changes through an event handler.
Controlled components keep form values in React state. The input value comes from state, and onChange updates that state. This makes the current form data available to the component for validation, conditional UI, and submission. Forms can manage multiple fields using one state object, separate state values, or other form abstractions. Validation should be clear and should provide useful feedback without relying only on placeholders. For larger forms, separating validation logic from rendering can keep components easier to maintain.
A student registration form can keep name, email, password, and selected course in React state and validate the fields before submission.
import { useState } from 'react';
export default function LoginForm() {
const [email, setEmail] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log(email);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit">Login</button>
</form>
);
}The email input is controlled by React state, and submitting the form logs the current email value.