Accessibility

Semantic HTML, ARIA, focus and checking it.

Builds on Refs.

React makes it very easy to build UI that looks right and works only for people using a mouse with good eyesight. A div with an onClick renders, responds to clicks, and is invisible to a keyboard and meaningless to a screen reader. None of that shows up as an error, and a visual review won't catch it.

The previous chapter already brushed against this: tests that query by role fail on inaccessible markup. This chapter is about building it right in the first place. It starts with how assistive technology actually sees your page (we'll build a tiny inspector), then covers semantic HTML, the rules of ARIA, accessible names, keyboard support, focus management for dialogs and route changes, live regions, two widgets built properly, and how to check all of it. Everything here is also what interviewers mean when they ask "how do you make a React app accessible?"

The problem: the screen reader doesn't see your screen#

Screen readers, voice control and switch devices don't look at pixels. The browser builds an accessibility tree from the DOM: for each meaningful element, a role (button, link, textbox, heading), an accessible name ("Save", "Email"), states (expanded, checked, disabled) and whether it can receive focus. Assistive technology reads that tree and nothing else.

Here's a small inspector that computes a simplified version of that tree, run over two versions of the same toolbar. Tab through the preview with your keyboard too.

A toy accessibility inspector
import { useEffect, useRef, useState } from "react";
import { inspect } from "./inspect";

function BadToolbar() {
  const [open, setOpen] = useState(false);
  return (
    <div>
      <div className="btn" onClick={() => console.log("saved")}>Save</div>
      <button onClick={() => console.log("deleted")}>
        <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 4h10M5 4V2h4v2M3 4l1 9h6l1-9" stroke="currentColor" fill="none" /></svg>
      </button>
      <span>Email</span> <input />
      <div className="btn" onClick={() => setOpen(!open)}>Details</div>
      {open && <p>Ships in 2 days.</p>}
    </div>
  );
}

function GoodToolbar() {
  const [open, setOpen] = useState(false);
  return (
    <div>
      <button onClick={() => console.log("saved")}>Save</button>
      <button aria-label="Delete" onClick={() => console.log("deleted")}>
        <svg aria-hidden="true" width="14" height="14" viewBox="0 0 14 14"><path d="M2 4h10M5 4V2h4v2M3 4l1 9h6l1-9" stroke="currentColor" fill="none" /></svg>
      </button>
      <label>Email <input type="email" /></label>
      <button aria-expanded={open} aria-controls="ship" onClick={() => setOpen(!open)}>Details</button>
      <p id="ship" hidden={!open}>Ships in 2 days.</p>
    </div>
  );
}

export default function App() {
  const bad = useRef<HTMLDivElement>(null);
  const good = useRef<HTMLDivElement>(null);
  useEffect(() => {
    console.log("BAD toolbar\n" + inspect(bad.current!));
    console.log("GOOD toolbar\n" + inspect(good.current!));
  }, []);
  return (
    <>
      <h4>Looks fine</h4>
      <div ref={bad}><BadToolbar /></div>
      <h4>Is fine</h4>
      <div ref={good}><GoodToolbar /></div>
    </>
  );
}
Nothing logged yet.

The two toolbars look nearly identical. In the tree they're different products. The bad one has a "Save" that is just text, a delete button with no name (a screen reader announces "button" and nothing else), an unnamed text box, and a "Details" control that can't be reached by keyboard and doesn't say whether it's open. The good one is the same markup with real elements and three attributes.

The DOM and the accessibility tree
What you renderWhat a screen reader gets<div onClick={save}>Save</div>generictext: Save, not focusable<button onClick={save}>Save</button>button "Save"focusable, Enter and Space
Step 1 of 4

Assistive technology doesn't read your DOM; it reads the accessibility tree the browser derives from it. A div with a click handler becomes an anonymous generic node: no role, no focus, no keyboard. A button comes with all three.

Semantic HTML first#

Most accessibility in React comes from using the element that already means what you want. Native elements bring their role, name source, focus behavior, keyboard handling and states for free, and they work with every assistive technology without testing:

NeedUseYou get
Do something<button>Focusable, Enter and Space activate, disabled works, role button
Go somewhere<a href>Focusable, Enter activates, open in new tab, role link
Text input<input> with <label>Name from the label, clicking the label focuses the input
Group of fields<fieldset> with <legend>The legend names the group (radio groups especially)
Page structure<header>, <nav>, <main>, <footer>Landmarks screen reader users jump between
Outline<h1> to <h6>, in orderThe page's table of contents; most screen reader users navigate by headings
Lists and tables<ul>, <ol>, <table> with <th>"List, 5 items", row and column headers announced
Modal<dialog> with showModal()Focus moved inside, Escape closes, rest of the page inert

The button-versus-link rule deserves a sentence of its own because React apps break it constantly: if it changes the URL, it's a link (your router's Link renders an <a>); if it does something on the page, it's a button. A <div onClick> is neither, and a <button onClick={() => navigate("/books")}> loses "open in new tab" and the link role.

ARIA: what it's for and its rules#

ARIA (Accessible Rich Internet Applications) is a set of attributes that change what the accessibility tree says: role, aria-label, aria-expanded, aria-controls, aria-live and so on. It changes only the tree. It adds no behavior: role="button" on a div doesn't make it focusable or respond to Enter. That's why the W3C's ARIA Authoring Practices guide puts it bluntly: no ARIA is better than bad ARIA. Wrong ARIA actively misinforms users, while missing ARIA on native elements usually costs nothing.

The rules, roughly in order of how often they're broken:

  1. Use a native element if one exists with the semantics and behavior you need. ARIA is for things HTML has no element for: tabs, comboboxes, tree views, menus, live updates.
  2. Don't change native semantics unless you must: <h2 role="button"> breaks the heading. Put a <button> inside the <h2> instead.
  3. Everything interactive with an ARIA role must be keyboard operable. If you write role="button", you also owe tabIndex={0} and Enter and Space handlers. (Or use a <button>.)
  4. Never hide focusable elements. aria-hidden="true" on something that can still receive focus creates a ghost: keyboard users land on it and screen readers say nothing.
  5. Every interactive element needs an accessible name.

In React, ARIA attributes are written exactly as in HTML (aria-expanded, not camelCase), and boolean-like ones accept JavaScript booleans: aria-expanded={open} renders "true" or "false". The useful mental split: roles say what something is, properties describe relationships (aria-controls, aria-describedby, aria-labelledby), and states change with interaction (aria-expanded, aria-pressed, aria-checked, aria-selected, aria-invalid). States are exactly the kind of thing React is good at: they're derived from your component's state on every render, so they can't drift.

Accessible names, and useId for connecting things#

Browsers compute an element's name from several sources, in a fixed order of precedence. Simplified:

  1. aria-labelledby: the text of the referenced elements (wins over everything).
  2. aria-label: a string.
  3. The native source: <label> for inputs, alt for images, <legend> for fieldsets, <caption> for tables.
  4. The element's own text content, for roles that take their name from content (buttons, links, headings).
  5. title (and placeholder for inputs) as a last resort.

Connecting a label, a hint and an error message to an input takes ids. In React those ids must be unique even when a component renders many times, and they must match between server and client rendering. That's what useId is for (Custom hooks shows how it derives ids from tree position). Never use Math.random() or a module-level counter: the server and the client would generate different ids, which is a hydration mismatch.

A field with a label, hint and error, wired with useId
import { useId, useState, type ComponentProps } from "react";

function Field({ label, hint, error, ...inputProps }: { label: string; hint?: string; error?: string } & ComponentProps<"input">) {
  const id = useId();
  const hintId = `${id}-hint`;
  const errorId = `${id}-error`;
  const describedBy = [hint && hintId, error && errorId].filter(Boolean).join(" ") || undefined;
  return (
    <div style={{ marginBottom: 12 }}>
      <label htmlFor={id}>{label}</label>
      <br />
      <input id={id} aria-describedby={describedBy} aria-invalid={error ? true : undefined} {...inputProps} />
      {hint && <div id={hintId} style={{ fontSize: 12, color: "#78716c" }}>{hint}</div>}
      {error && <div id={errorId} style={{ fontSize: 12, color: "#b4532a" }}>{error}</div>}
    </div>
  );
}

export default function App() {
  const [year, setYear] = useState("");
  const error = year && !/^\d{4}$/.test(year) ? "Use a four-digit year, like 1999." : undefined;
  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <Field label="Title" hint="As printed on the cover." />
      <Field label="Year" value={year} onChange={(e) => setYear(e.target.value)} error={error} inputMode="numeric" />
      <Field label="Year (second copy)" hint="Same component, different ids." />
    </form>
  );
}

Inspect the inputs in your browser's DevTools (the Accessibility pane in Chrome or Firefox shows the computed tree). The year field's description is its error message, it's marked invalid, and each instance of Field got its own ids. A screen reader announces "Year, edit text, invalid entry, Use a four-digit year, like 1999".

Keyboard support#

Everything you can do with a mouse must be possible with a keyboard. Native controls get this for free. For your own widgets, the conventions are:

  • Tab and Shift+Tab move between interactive elements in DOM order. Keep DOM order equal to visual order; CSS that reorders content (order, absolute positioning) makes focus jump around.
  • tabIndex: 0 puts a non-native element in the tab order, -1 makes it focusable from code but not by Tab (for headings you focus after navigation, or items in a composite widget). Never use positive values: they override the natural order for the whole page.
  • Composite widgets (tabs, menus, listboxes, toolbars, grids) are one tab stop. Inside, arrow keys move. Implement it with a roving tabindex (the active item has tabIndex={0}, the rest -1, and focus moves with the arrows) or with aria-activedescendant (focus stays on a container or input, which points at the active item's id).
  • Escape closes whatever popped up, and focus goes back to what opened it.
  • Focus must be visible. Don't remove outlines; style them. :focus-visible shows a ring for keyboard focus without showing it on mouse clicks.

Focus management#

A screen reader user's "where am I" is the focused element. When your UI changes context, you have to move focus deliberately, because the browser won't.

Dialogs. Opening a modal must move focus into it, keep Tab inside it, make the rest of the page unreachable, close on Escape, and return focus to the control that opened it. Hand-rolling all of that is how most inaccessible modals are born. The native <dialog> element opened with showModal() does most of it: it moves focus to the first focusable element (or the one with autoFocus), renders in the top layer, makes everything outside it inert, and closes on Escape. React just needs to call the imperative methods, which is a job for a ref and an effect:

A modal with the native dialog element
import { useEffect, useId, useRef, useState, type ReactNode } from "react";

function Modal({ open, onClose, title, children }: { open: boolean; onClose: () => void; title: string; children: ReactNode }) {
  const ref = useRef<HTMLDialogElement>(null);
  const titleId = useId();

  // Sync React state to the imperative dialog API.
  useEffect(() => {
    const dialog = ref.current!;
    if (open && !dialog.open) dialog.showModal();
    if (!open && dialog.open) dialog.close();
  }, [open]);

  // "close" fires for Escape, form method="dialog", and dialog.close().
  return (
    <dialog ref={ref} aria-labelledby={titleId} onClose={onClose} style={{ borderRadius: 8, border: "1px solid #a8a29e" }}>
      <h2 id={titleId} style={{ marginTop: 0 }}>{title}</h2>
      {children}
    </dialog>
  );
}

export default function App() {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("Refactoring");
  const opener = useRef<HTMLButtonElement>(null);
  return (
    <>
      <p>Current title: {title}</p>
      <button ref={opener} onClick={() => setOpen(true)}>Edit title</button>
      <p><a href="#">A link behind the dialog (try to Tab to it while open)</a></p>
      <Modal
        open={open}
        title="Edit title"
        onClose={() => {
          setOpen(false);
          opener.current?.focus(); // return focus to where the user was
        }}
      >
        <form method="dialog">
          <label>
            Title <input value={title} onChange={(e) => setTitle(e.target.value)} />
          </label>{" "}
          <button>Done</button>
        </form>
      </Modal>
    </>
  );
}

Open it with the keyboard, press Tab a few times (focus stays inside), then press Escape: focus lands back on Edit title. Browsers increasingly restore focus to the opener on their own, but doing it explicitly costs one line and covers older ones. For non-modal popovers, the popover attribute gives you light dismiss and top-layer rendering with similar ease. And if you need more (nested dialogs, animated exits, scroll locking quirks), use a headless library such as Radix or React Aria, which handle these cases.

Route changes. In a multi-page site, every navigation loads a new document and screen readers start reading from the top. A client-side router swaps content without that signal: focus stays on the link you clicked (which may no longer exist) and nothing is announced. Two fixes, often combined: move focus to the new page's main heading, and announce the new page title through a live region. Next.js's App Router includes a route announcer that does the announcing for you. With React Router or TanStack Router, a small component does the focusing:

PageHeading.tsx
import { useEffect, useRef } from "react";
import { useLocation } from "react-router";

export function PageHeading({ children }: { children: React.ReactNode }) {
  const ref = useRef<HTMLHeadingElement>(null);
  const { pathname } = useLocation();
  useEffect(() => {
    ref.current?.focus(); // tabIndex -1: focusable by code, not by Tab
  }, [pathname]);
  return (
    <h1 ref={ref} tabIndex={-1} style={{ outline: "none" }}>
      {children}
    </h1>
  );
}

Live regions: announcing changes#

Some updates happen away from focus: "Saved", "3 results", a validation summary, a toast. Sighted users see them; screen reader users hear nothing unless the update is in a live region. An element with aria-live="polite" (or role="status", which implies polite) is announced when its content changes, after the screen reader finishes its current sentence. aria-live="assertive" (or role="alert") interrupts, so save it for errors that need attention now.

The detail that trips people up in React: the live region must already be in the DOM before its content changes. Mounting <p role="status">Saved</p> at the same moment as its text is often not announced, because there was no change to a region the screen reader was watching. Render the container always, and change its text.

A status message that gets announced
import { useState } from "react";
import { books } from "guide-tools";

export default function App() {
  const [list, setList] = useState<string[]>([]);
  const [message, setMessage] = useState("");

  function add(title: string) {
    if (list.includes(title)) {
      setMessage(`${title} is already on your list.`);
      return;
    }
    const next = [...list, title];
    setList(next);
    setMessage(`Added ${title} to your list. ${next.length} books saved.`);
  }

  return (
    <div>
      {books.slice(0, 3).map((b) => (
        <button key={b.id} onClick={() => add(b.title)} style={{ display: "block", marginBottom: 6 }}>
          Add {b.title}
        </button>
      ))}
      {/* Always rendered; only its text changes. */}
      <p role="status" style={{ minHeight: 20, color: "#4f7a5d" }}>{message}</p>
    </div>
  );
}

Two widgets, built properly#

A disclosure#

A disclosure (show/hide section) is the simplest custom widget: a button with aria-expanded, pointing at the panel it controls with aria-controls. You'll build it in the exercises below.

Combobox basics#

A combobox (an input with a popup list of suggestions) is one of the hardest widgets to get right, which is exactly why it's a good one to read. Focus stays in the input the whole time; the list is a listbox of options; the input points at the highlighted option with aria-activedescendant, so the screen reader announces it while the caret stays in the text field.

Combobox basics
import { useId, useState, type KeyboardEvent } from "react";
import { books } from "guide-tools";

export default function App() {
  const id = useId();
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(-1);
  const [picked, setPicked] = useState("");

  const matches = books.filter((b) => b.title.toLowerCase().includes(query.toLowerCase())).slice(0, 6);
  const optionId = (i: number) => `${id}-option-${i}`;

  function choose(i: number) {
    const book = matches[i];
    if (!book) return;
    setQuery(book.title);
    setPicked(book.title);
    setOpen(false);
    setActive(-1);
  }

  function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setOpen(true);
      setActive((i) => Math.min(i + 1, matches.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActive((i) => Math.max(i - 1, 0));
    } else if (e.key === "Enter" && open && active >= 0) {
      e.preventDefault();
      choose(active);
    } else if (e.key === "Escape") {
      setOpen(false);
      setActive(-1);
    }
  }

  return (
    <div>
      <label htmlFor={`${id}-input`}>Book</label>{" "}
      <input
        id={`${id}-input`}
        role="combobox"
        aria-autocomplete="list"
        aria-expanded={open}
        aria-controls={`${id}-listbox`}
        aria-activedescendant={open && active >= 0 ? optionId(active) : undefined}
        value={query}
        onChange={(e) => {
          setQuery(e.target.value);
          setOpen(true);
          setActive(-1);
        }}
        onKeyDown={onKeyDown}
        onBlur={() => setOpen(false)}
      />
      <ul id={`${id}-listbox`} role="listbox" aria-label="Books" hidden={!open || matches.length === 0} style={{ listStyle: "none", padding: 0, border: "1px solid #d6d3d1", maxWidth: 320 }}>
        {matches.map((b, i) => (
          <li
            key={b.id}
            id={optionId(i)}
            role="option"
            aria-selected={i === active}
            onMouseDown={(e) => e.preventDefault()} // keep focus in the input
            onClick={() => choose(i)}
            style={{ padding: "4px 8px", background: i === active ? "#f6e3d8" : undefined, cursor: "pointer" }}
          >
            {b.title}
          </li>
        ))}
      </ul>
      <p role="status">{open ? `${matches.length} suggestions` : picked && `Selected ${picked}`}</p>
    </div>
  );
}

Try it with only the keyboard: type "the", arrow down and up, Enter to choose, Escape to close. Notice what each attribute does. aria-expanded tells the user the popup is open. aria-controls links input and list. aria-activedescendant makes the highlighted option the one announced, without moving focus. aria-selected marks it in the list. onMouseDown with preventDefault stops the input from blurring when an option is clicked. And the status line announces how many suggestions there are.

This is "basics" on purpose. A production combobox also handles async results, grouping, scrolling the active option into view, mobile screen readers, IME composition and more. Use React Aria's ComboBox, Radix, Headless UI or Downshift, and spend your effort on the product.

Checking it#

Accessibility checks belong at every layer from the last chapter:

  • Lint: eslint-plugin-jsx-a11y flags missing alt, click handlers on static elements without keyboard handlers, invalid ARIA attributes and roles, and more, as you type.

  • Component tests: querying by role and name (getByRole("button", { name: "Delete" })) fails when the role or name is missing. Add axe-core through vitest-axe or jest-axe for an automated rule scan of a rendered component:

    import { axe } from "vitest-axe";
    import "vitest-axe/extend-expect"; // registers toHaveNoViolations; usually done once in the setup file
    
    test("the toolbar has no detectable a11y violations", async () => {
      const { container } = render(<Toolbar />);
      expect(await axe(container)).toHaveNoViolations();
    });
  • End to end: @axe-core/playwright scans whole pages in a real browser, including color contrast, which jsdom can't compute: const results = await new AxeBuilder({ page }).analyze(); expect(results.violations).toEqual([]);.

  • Manually, because automated tools only catch part of the problems (they can tell an image has no alt, not that the alt is useless). Do a keyboard-only pass of every new flow: can you reach everything, see where focus is, and get out of every popup? Then try a screen reader: VoiceOver on macOS and iOS, NVDA on Windows, TalkBack on Android. Browser DevTools' accessibility pane shows the computed tree, like our inspector but complete.

Pitfalls#

Check your understanding#

Build itAn accessible disclosure

Turn this clickable div into an accessible disclosure: a real <button> labelled with title, aria-expanded reflecting the state, aria-controls pointing at the panel's id (use useId), and a panel that's hidden when closed.

import { useId, useState, type ReactNode } from "react";

function Disclosure({ title, children }: { title: string; children: ReactNode }) {
  const [open, setOpen] = useState(false);
  // TODO: make this accessible
  return (
    <div>
      <div onClick={() => setOpen(!open)} style={{ cursor: "pointer", fontWeight: 600 }}>
        {open ? "▾" : "▸"} {title}
      </div>
      {open && <div>{children}</div>}
    </div>
  );
}

export default function App() {
  return (
    <>
      <Disclosure title="Shipping details">Ships in 2 days.</Disclosure>
      <Disclosure title="Returns">Free returns for 30 days.</Disclosure>
    </>
  );
}
Fix itA modal that loses keyboard users

This "modal" is a div. When it opens, focus stays on the Edit title button behind it; Tab wanders into the page; and after Done, focus is dropped on the page body. Rebuild it on the native <dialog> with showModal(), and return focus to the opener when it closes.

import { useState } from "react";

export default function App() {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("Refactoring");
  return (
    <>
      <p>Current title: {title}</p>
      <button onClick={() => setOpen(true)}>Edit title</button>
      {open && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.3)", display: "grid", placeItems: "center" }}>
          <div style={{ background: "white", padding: 16, borderRadius: 8 }}>
            <h2>Edit title</h2>
            <label>
              Title <input value={title} onChange={(e) => setTitle(e.target.value)} />
            </label>{" "}
            <button onClick={() => setOpen(false)}>Done</button>
          </div>
        </div>
      )}
    </>
  );
}
PredictWhat's it called?

Predict the accessible name a screen reader announces for each element.

// 1
<button aria-label="Close"><span>×</span></button>

// 2
<h2 id="billing">Billing</h2>
<button aria-labelledby="billing">Edit</button>

// 3
<label htmlFor="q">Search books</label>
<input id="q" placeholder="Title or author" />

// 4
<img src="/divider.svg" alt="" />

// 5
<button><svg aria-hidden="true">…</svg></button>
Quick checkFixing a clickable div

A teammate fixes a clickable Save div by adding role button to it, and nothing else. What's still broken?

Explain it out loudAn accessible modal

"Walk me through making a modal dialog accessible in React."

Interview angle

Say it in 30 seconds

Assistive technology reads the accessibility tree the browser derives from the DOM: each element's role, accessible name, states and focusability. So accessibility in React starts with semantic HTML: buttons for actions, links for navigation, labels for inputs, headings and landmarks, the dialog element for modals. ARIA only changes semantics, never behavior, so no ARIA is better than bad ARIA. Every control needs a name and keyboard support, with useId to wire labels and descriptions. Focus has to be managed when context changes, like dialogs and client-side route changes, and off-focus updates go through live regions. Check it with lint rules, role queries, axe and manual keyboard and screen reader passes.

How do you make a React app accessible?

basic

What does 'no ARIA is better than bad ARIA' mean?

intermediate

What is an accessible name, and how is it computed?

intermediate

What happens to focus on a client-side route change, and what should you do about it?

senior

How do you announce an update that happens away from focus, like 'Saved'?

intermediate

How should keyboard navigation work in a custom listbox, menu or tab list?

senior

Recap#

  • Assistive technology reads the accessibility tree: role, accessible name, states and focusability, derived from your DOM. What it looks like doesn't matter to it.
  • Semantic HTML first: buttons for actions, links for navigation, labels for inputs, headings and landmarks for structure, <dialog> for modals. ARIA changes semantics only, never behavior, so no ARIA beats bad ARIA.
  • Every interactive element needs a name (label, content, aria-label, aria-labelledby) and must work with the keyboard; composite widgets are one tab stop with arrow keys inside. Use useId to connect labels, hints and errors.
  • Manage focus on context changes: into and out of dialogs, to the heading after client-side navigation. Announce off-focus updates through live regions that are already mounted.
  • Check with jsx-a11y, role-based queries, axe in component and E2E tests, and manual keyboard and screen reader passes.

Sources#