QReact · Interview preparation
How should a React form display validation errors?
Associate each error message with its input and make the next action clear.
The idea to remember.
Associate each error message with its input and make the next action clear. Keep the user's entered values and move focus to an error summary when submitting a long form fails.
01Learn by doing
From first example to real project.
Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.
Basic: controlled input
01 / BEGINNERKeep the visible value in React state.
function NameField() {
const [name, setName] = React.useState('');
return <input value={name} onChange={e => setName(e.target.value)} />;
}Intermediate: validate on submit
02 / INTERMEDIATEUse built-in form semantics and show actionable errors.
function Signup() {
function submit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
if (!String(data.get('email')).includes('@')) return;
// Send validated form data to the server.
}
return <form onSubmit={submit}><label>Email <input name="email" type="email" required /></label><button>Join</button></form>;
}Real scenario: save safely
03 / REAL SCENARIODisable duplicate submissions, surface failures and preserve input.
async function submitProfile(formData, setSaving, setError) {
setSaving(true);
setError('');
try {
const response = await fetch('/api/profile', { method: 'POST', body: formData });
if (!response.ok) throw new Error('Could not save');
} catch (error) { setError(error.message); }
finally { setSaving(false); }
}02Check your understanding
Try it in your own words.
Explain how should a React form display validation errors without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.
Keep learning here.
Explore more in-depth guides, exercises and related interview questions in this library.
Browse React study guides ↗