A label, an input and an error message belong together, and assistive
technology needs to know it. HTML connects them with ids: <label htmlFor>
points at an input's id, and aria-describedby points at the element that
describes it, such as an error. Hard-coded ids break when a component is used
twice on a page. useId makes a unique one for each use.
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Press Save with the fields empty. Then fill in a title and press Save
again.
useId
JavaScript
const id = useId();const errorId = `${id}-error`;
Field is used twice, and each call to useId returns a different id, stable
across renders. The label's htmlFor and the input's id match, so clicking
the label focuses the input, and screen readers read the label with it:
Don't use useId for list keys. Keys come from your data.
Errors that are announced
When a field has an error, the input gets:
aria-invalid={true}, which announces "invalid";
aria-describedby={errorId}, which reads the error message after the label.
Focus the first problem
When validation fails, handleSubmit focuses the first invalid field, with
a ref passed through Field. Keyboard and screen reader users land exactly
where the problem is, instead of hunting for a red message. Fix the title and
save again: focus now moves to Minutes, the next problem:
JavaScript
function handleSubmit(event) { event.preventDefault(); const found = {}; if (title.trim() === "") found.title = "Enter a title."; const amount = Number(minutes); if (!Number.isInteger(amount) || amount <= 0) found.minutes = "Enter whole minutes above 0."; setErrors(found); if (found.title) { titleRef.current.focus(); return; } if (found.minutes) { minutesRef.current.focus(); return; } setSaved(`${title.trim()}, ${amount} minutes`);}
noValidate on the form turns off the browser's own validation bubbles, so
these messages are the only ones shown.
Exercise
Check the wiring
Open your browser's developer tools on this page, find the lab's preview frame,
and inspect the Minutes input after a failed save. Write down its id and
aria-describedby, and the id of the red message. Which element does each
point to?
Hint 1: the idea
A label names the field; a description explains it. Each reference must lead to an existing element in this preview.
Hint 2: a first step
The ids look like _r_0_. React generates them, so don't rely on the exact
text. What matters is that they match each other.
Show one solution
The input's id equals the label's htmlFor. Its aria-describedby equals
the id of the <span> holding the error, which is the input's id followed by
-error. The two Fields have different ids, so each error describes only its
own input.
Completion is saved in this browser only. It does not measure mastery.