Sub topic 10
Showing errors and tracking touched fields
This chapter assumes you can write a controlled form with one state object and a pure validate function, as in the earlier chapters. It adds the rule for when an error should appear.
The problem with showing errors immediately
If you render every error as soon as validation fails, the form looks broken before the user types anything. An empty email field is invalid, but the user has not had a chance to fill it in yet. Showing "Enter a valid email address." on first render is noise.
The fix is to track which fields the user has finished with. Such a field is called touched. A field becomes touched when it loses focus, which React reports through the onBlur event.
Deriving errors instead of storing them
Compute the errors object during render from the current values. Do not keep it in state. State holds only what cannot be derived: the values, the touched flags, and whether a submit was attempted. This removes a class of bugs where errors lags one render behind values.
import { useState } from 'react';
function validate(values) {
const errors = {};
if (!values.email.includes('@')) {
errors.email = 'Enter a valid email address.';
}
if (values.password.length < 8) {
errors.password = 'Use at least 8 characters.';
}
return errors;
}
export default function LoginForm() {
const [values, setValues] = useState({ email: '', password: '' });
const [touched, setTouched] = useState({});
const [submitted, setSubmitted] = useState(false);
const errors = validate(values);
function handleChange(e) {
setValues((prev) => ({ ...prev, [e.target.name]: e.target.value }));
}
function handleBlur(e) {
const { name } = e.target;
setTouched((prev) => ({ ...prev, [name]: true }));
}
function handleSubmit(e) {
e.preventDefault();
setSubmitted(true);
if (Object.keys(errors).length === 0) {
console.log('Valid', values);
}
}
function showError(name) {
return (touched[name] || submitted) && errors[name];
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
{showError('email') && <p role="alert">{errors.email}</p>}
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
/>
{showError('password') && <p role="alert">{errors.password}</p>}
<button type="submit">Log in</button>
</form>
);
}How the rule works
The helper showError returns a message only when two conditions hold. The field must be touched or a submit must have been attempted, and the field must currently have an error.
The submitted flag matters. A user who clicks "Log in" without visiting the password field has never blurred it, so touched.password is still unset. Without submitted, the form would refuse to submit and show nothing.
Common mistakes
- Marking touched in
onChange. The error then appears while the user types the first character. UseonBlur. - Storing
errorsin state. It can drift out of sync withvalues. Derive it on each render. - Forgetting to reset flags. After a successful submit or a form reset, set
touchedto{}andsubmittedtofalse, or old errors will reappear.
Exercise
A user opens the form above and clicks "Log in" without typing anything. Which errors appear, and why? Which flag makes this happen?
Show answer
Both the email and password errors appear. No field was blurred, so touched is empty, but the submit handler sets submitted to true. showError returns the message when either touched[name] or submitted is true and the field has an error.
Exercise
Why is it better to compute errors with validate(values) during render than to call setErrors inside handleChange?
Show answer
The derived errors always match the current values. With setErrors you must remember to call it in every place that changes values, such as a reset, and a missed call leaves stale messages on screen.