Controlled Forms
Controlled inputs, form state, validation, and submission
Skills taught: react.controlled-inputs, react.form-state, react.form-validation, react.form-submission
Controlled form with validation
function RegisterForm() {
const [form, setForm] = useState({ name: '', email: '', password: '', age: '' });
const [errors, setErrors] = useState({});
const [submitted, setSubmitted] = useState(false);
const update = (field, value) => {
setForm(prev => ({ ...prev, [field]: value }));
if (errors[field]) setErrors(prev => ({ ...prev, [field]: '' }));
};
const validate = () => {
const errs = {};
if (!form.name.trim()) errs.name = 'Name is required';
if (!/^[^@]+@[^@]+\.[^@]+$/.test(form.email)) errs.email = 'Valid email required';
if (form.password.length < 8) errs.password = 'At least 8 characters';
if (Number(form.age) < 18) errs.age = 'Must be 18 or older';
return errs;
};
const handleSubmit = (e) => {
e.preventDefault();
const errs = validate();
if (Object.keys(errs).length > 0) { setErrors(errs); return; }
setSubmitted(true);
};
if (submitted) {
return (
<div style={{ fontFamily: 'sans-serif', padding: '12px', background: '#dcfce7', borderRadius: '8px' }}>
<h3>✅ Registered successfully!</h3>
<p>Welcome, {form.name}!</p>
<button onClick={() => { setForm({ name:'', email:'', password:'', age:'' }); setSubmitted(false); }}>Register Another</button>
</div>
);
}
const Field = ({ name, label, type = 'text', ...rest }) => (
<div style={{ marginBottom: '10px' }}>
<label style={{ display: 'block', fontSize: '0.85rem', fontWeight: '500', marginBottom: '4px' }}>{label}</label>
<input
type={type}
value={form[name]}
onChange={e => update(name, e.target.value)}
style={{ width: '100%', padding: '8px', border: `1px solid ${errors[name] ? '#ef4444' : '#d1d5db'}`, borderRadius: '6px', boxSizing: 'border-box' }}
{...rest}
/>
{errors[name] && <p style={{ color: '#ef4444', fontSize: '0.78rem', margin: '4px 0 0' }}>{errors[name]}</p>}
</div>
);
return (
<form onSubmit={handleSubmit} style={{ fontFamily: 'sans-serif', padding: '8px', maxWidth: '320px' }}>
<h2>Create Account</h2>
<Field name="name" label="Full Name" placeholder="Alice Singh" />
<Field name="email" label="Email" type="email" placeholder="alice@example.com" />
<Field name="password" label="Password" type="password" placeholder="Min 8 chars" />
<Field name="age" label="Age" type="number" min={0} />
<button type="submit" style={{ width: '100%', padding: '10px', background: '#4fd1c5', border: 'none', borderRadius: '6px', fontWeight: 'bold', cursor: 'pointer' }}>Register</button>
</form>
);
}
function App() {
return <RegisterForm />;
}
Frequently Asked Questions
Should I use a library like react-hook-form?
For production apps with many forms, yes — react-hook-form dramatically reduces boilerplate, is performant (no re-render per keystroke), and integrates with validation schemas (Zod, Yup). For learning React or simple single-field scenarios, manual controlled inputs are fine and educational. Knowing how controlled inputs work helps you understand what libraries like react-hook-form are doing under the hood.