sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEFoundation3 min read

How should a React form display validation errors?

Associate each error message with its input and make the next action clear.

React#forms#accessibility
THE ANSWER / PLAIN ENGLISH

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.

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 / BEGINNER

Keep the visible value in React state.

JSX / EXAMPLE
function NameField() {
  const [name, setName] = React.useState('');
  return <input value={name} onChange={e => setName(e.target.value)} />;
}

Intermediate: validate on submit

02 / INTERMEDIATE

Use built-in form semantics and show actionable errors.

JSX / EXAMPLE
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 SCENARIO

Disable duplicate submissions, surface failures and preserve input.

JSX / EXAMPLE
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); }
}

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 ↗
← Back to question library

Have something
in mind?

Start a conversation