Skip to content

useId and Accessible Fields

The Course
•
15 min study

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.

Labelled fields with errors React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useRef, useState } from "react"; import Field from "./Field.jsx"; export default function App() { const [title, setTitle] = useState(""); const [minutes, setMinutes] = useState(""); const [errors, setErrors] = useState({}); const [saved, setSaved] = useState(""); const titleRef = useRef(null); const minutesRef = useRef(null); 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`); } return ( <main> <h1>New card</h1> <form onSubmit={handleSubmit} noValidate> <Field ref={titleRef} label="Title" value={title} onChange={setTitle} error={errors.title} /> <Field ref={minutesRef} label="Minutes" type="number" value={minutes} onChange={setMinutes} error={errors.minutes} /> <button type="submit">Save</button> </form> {saved && <p>Saved: {saved}</p>} </main> ); } import { useId } from "react"; // A labelled input. useId gives each instance its own ids, so the label and // the error message point at the right input even when the field is reused. export default function Field({ ref, label, value, onChange, error, type = "text" }) { const id = useId(); const errorId = `${id}-error`; return ( <p> <label htmlFor={id}>{label}</label>{" "} <input ref={ref} id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} aria-invalid={error ? true : undefined} aria-describedby={error ? errorId : undefined} /> {error && <span id={errorId} className="error"> {error}</span>} </p> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
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:

JSX
return (
  <p>
    <label htmlFor={id}>{label}</label>{" "}
    <input
      ref={ref}
      id={id}
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      aria-invalid={error ? true : undefined}
      aria-describedby={error ? errorId : undefined}
    />
    {error && <span id={errorId} className="error"> {error}</span>}
  </p>
);

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.

Was this article helpful?

Your response is saved on this device.