Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 132 ยท Advanced Patterns

Accessibility in React

Build accessible React apps: semantic HTML, labels, focus management, ARIA, keyboard navigation, live regions and a custom tabs widget that works for everyone.

Accessibility (often written a11y) means that people can use your interface whatever way they interact with it: with a mouse, a keyboard only, a screen reader, voice control, a switch device, a zoomed screen or a slow connection. About one person in six lives with a disability, and everyone is temporarily "disabled" at some point: a broken wrist, a bright sun on the screen, a noisy train.

React does not make this harder than plain HTML, and it does not make it automatic either. React renders the same DOM that a browser understands, so everything you know about accessible HTML still applies. What React adds is a few spelling rules (htmlFor, aria-*, tabIndex) and a component model that makes it easy to build an accessible widget once and reuse it everywhere. This lesson shows the habits that give you 90% of the result, then builds a custom widget with full keyboard support.

Start with semantic HTML

The most important accessibility rule in React is the same as in HTML: use the element that means what you want. A <button> is focusable, activates with Enter and Space, announces itself as a button, and can be disabled. A <div onClick> does none of that.

div versus button

Click the editor preview first, then press Tab. The focus ring lands on the real button and skips the div. To make the div as usable you would have to add role="button", tabIndex={0}, a key handler for Enter and Space, and focus styles, and you would still miss form-submit and disabled behaviour. Just use a <button>.

A short guide to choosing elements:

You want Use Not
An action on the page <button type="button"> <div onClick>
Navigation to another page or URL <a href> <span onClick>
A page title and sections <h1>-<h6>, <section>, <nav>, <main> <div className="title">
A list of items <ul> / <ol> with <li> a pile of <div>s
Tabular data <table> with <th scope> CSS grid made of <div>s

Landmarks such as <main>, <nav>, <header> and <footer> let screen reader users jump straight to the part of the page they need. A good React layout component renders them once, and your pages fill in the contents. Keep heading levels in order (one h1, then h2 below it, and so on); do not pick a heading by its size, since CSS controls size.

Fragments (<>...</>) are your friend here. They let a component return several sibling elements, such as a <dt> and a <dd> or a <li> pair, without adding a wrapper <div> that would break the HTML structure.

Labels for every control

Every form control needs an accessible name. The best name is a visible <label>. In JSX the HTML for attribute is spelled htmlFor, because for is a reserved word in JavaScript.

There are two correct ways to connect a label and its control. One is nesting the input inside the label. The other is htmlFor plus an id. In a reusable component you cannot hardcode an id (two copies would collide), so use useId, which generates one that is unique and stable per component instance.

Labels with useId

Click the words "First name" and the input gets focus. That click-through is the label doing its job, and it enlarges the click target, which helps people with motor impairments. The hint is linked with aria-describedby, so a screen reader reads it after the label and the value.

If a control has no visible text, for example an icon button, give it an accessible name with aria-label:

JSX
<button type="button" aria-label="Close dialog" onClick={onClose}>
  <CloseIcon aria-hidden="true" />
</button>

aria-hidden="true" on the decorative icon stops it from being announced twice. Images need alt text: describe the purpose of an informative image, and use alt="" for purely decorative ones.

Managing focus

Keyboard and screen reader users move through the page by focus. In a single-page app you change the page without a browser navigation, so the browser does not move focus for you. When content appears or disappears, you decide where focus goes. Two rules cover most cases:

  1. When something opens (a dialog, a menu, an inline editor), move focus into it.
  2. When it closes, return focus to the control that opened it.

Refs make this easy. See Refs with useRef for the basics.

Move focus on open, restore on close

Click "Edit title": the input appears with its text selected and you can type immediately. Press Enter or Escape and the focus returns to the "Edit title" button, so a keyboard user is not dropped back at the top of the page. Without that last step, the button that had focus no longer exists, and the browser moves focus to document.body.

Other focus guidelines:

  • Never remove the focus outline (outline: none) without replacing it. A visible focus indicator is a WCAG requirement. Use :focus-visible to show it for keyboard users only.
  • Avoid positive tabIndex values. tabIndex={0} adds an element to the natural order, tabIndex={-1} makes it focusable by script only, and anything above 0 breaks the natural order.
  • Do not autofocus on page load unless the user obviously expects it.
  • After a route change in a single-page app, move focus to the new page heading (give it tabIndex={-1}) or announce the new title. See Client-Side Routing.

ARIA: a supplement, not a replacement

ARIA (Accessible Rich Internet Applications) attributes add meaning that HTML cannot express: roles (role="tablist"), states (aria-expanded, aria-selected, aria-checked) and properties (aria-label, aria-controls). In JSX they keep their hyphenated names, since they are plain DOM attributes.

The first rule of ARIA is do not use ARIA if a native element does the job. A native <button> beats <div role="button">, and <details> beats a hand-made disclosure. The second rule: ARIA changes only what assistive technology is told, never behavior. A role="button" on a div promises that Enter and Space work, and your code has to deliver that.

Values in ARIA that look like booleans are strings. React renders aria-expanded={true} as aria-expanded="true", which is what you want, while aria-expanded={undefined} leaves the attribute out. For boolean states pass a real boolean (React stringifies it for aria-* attributes).

A disclosure with aria-expanded

Open "Shipping", then press "Log aria-expanded values". The console prints aria-expanded values: true, false. A screen reader says "Shipping, button, expanded" and then "Returns, button, collapsed". The hidden attribute removes the closed panel from both the screen and the accessibility tree, which is why we used it rather than just styling it away with opacity.

Keyboard navigation in custom widgets

Native elements get keyboard support for free. When you build a custom widget (tabs, menus, listboxes, toolbars), you must implement the keyboard model users already know from the operating system. The ARIA Authoring Practices Guide documents these patterns. The most common trick is a roving tabindex: only one item in the group is in the Tab order (tabIndex={0}), the others are -1, and the arrow keys move the focus. That way Tab skips over the whole group instead of making the user press it 20 times.

A radio toolbar with arrow keys

Tab to the group, then use the arrow keys, Home and End. Tab leaves the group in one press because only one radio has tabIndex={0}. The % SIZES.length wrapping keeps the focus on the group at both ends. In a real project you would simply use <input type="radio">, which does all of this natively; build your own only when the design cannot be done with native controls.

Always call preventDefault() on keys you handle, such as arrows and Space, or the browser also scrolls the page. And never trap the keyboard: users must always be able to Tab or press Escape to leave a widget.

Live regions: announcing changes

Sighted users see a toast, a "3 results found" label or a validation message appear. Screen reader users only hear what is announced. A live region is an element that screen readers watch: when its text changes, they read the change aloud. Use role="status" (polite, waits for a pause) for non-urgent news and role="alert" (assertive, interrupts) for errors.

The container must exist in the DOM before its content changes, otherwise some readers announce nothing. So render the region always, and change only its text.

A polite status region

Type b and the message becomes "3 results" (banana, blueberry, cranberry); a screen reader says that without moving focus. The paragraph is rendered even when the message is empty, which matters. Do not use aria-live on large regions (a whole list) or announce on every keystroke of a fast-changing value: it turns into noise. Debounce or summarize.

Keyboard users should not have to Tab through a 30-link navigation on every page. A skip link is the first focusable element and jumps past the repeated content. It is usually visually hidden until it receives focus.

JSX
<a href="#main" className="skip-link">Skip to main content</a>
<header>{/* navigation */}</header>
<main id="main" tabIndex={-1}>{/* page content */}</main>

In CSS, the link sits off screen (position: absolute; left: -9999px) and moves into view on :focus. The tabIndex={-1} on main lets the target take focus when the link is followed. In a framework the router often handles focus for you, but check with the keyboard.

Also set a meaningful <title> for each page. React 19 lets any component render a <title> and hoists it into <head>.

Building an accessible custom widget

Let us put it together: a tabs component with the proper roles, linked ids from useId, a roving tabindex and keyboard support. Compare it with the version in Compound Components and Slots, which shares state through context.

Accessible tabs

Tab into the tab list, press the right arrow a few times, and notice that Tab then jumps straight to the active panel (it has tabIndex={0} so keyboard users can scroll it). All panels stay in the DOM and only hidden changes, which keeps aria-controls valid and preserves state inside each panel.

Testing accessibility

Automatic tools find perhaps a third of the problems, but they are cheap, so use them:

  • eslint-plugin-jsx-a11y flags missing alt text, click handlers on non-interactive elements and invalid ARIA while you type.
  • axe (the engine behind browser extensions and jest-axe or Playwright integrations) audits the rendered DOM. This is read-only advice, since the editor here cannot install packages:
Terminal
npm install --save-dev eslint-plugin-jsx-a11y jest-axe
JavaScript
// A test using jest-axe (read-only: needs a test setup)
import { axe } from 'jest-axe';

test('the form has no detectable violations', async () => {
  const { container } = render(<SignupForm />);
  expect(await axe(container)).toHaveNoViolations();
});

Then do the manual checks, which matter more:

  1. Unplug the mouse. Can you do everything with Tab, Shift+Tab, Enter, Space, arrows and Escape? Is the focus always visible?
  2. Zoom the page to 200% and shrink the window. Does it still work without horizontal scrolling?
  3. Turn on a screen reader (NVDA on Windows, VoiceOver on macOS) for five minutes on your main flow.
  4. Check contrast: text needs at least 4.5:1 against its background.
  5. Respect prefers-reduced-motion (see Animation and Transitions).

Common mistakes

  • <div onClick> instead of <button>, and <a> without href used as a button.
  • Placeholder text as the only label. It disappears when typing and has poor contrast.
  • Conveying meaning by colour alone, such as a red border for errors with no text.
  • outline: none with no replacement.
  • Unlabelled icon buttons.
  • Dialogs that do not move focus in, or let it escape into the page behind (see Portals and Overlays).
  • Updating the UI on route change with no focus or title change.
  • Writing aria-* attributes by guess. A wrong role is worse than none.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which element should you use for an action that does not navigate, such as saving a form section?

    A button is focusable, works with Enter and Space and is announced correctly without extra code. A clickable div needs role, tabIndex, key handlers and focus styles to come close.
  2. 2. Why do reusable components use useId for the htmlFor and id pair of a label and input?

    A hard-coded id would be duplicated if the component renders twice. useId returns a stable unique string per instance. Its exact value is opaque, so never depend on its format.
  3. 3. A dialog closes and the button that opened it still exists. What should you do with focus?

    Returning focus to the opener lets keyboard and screen reader users continue where they were. When focus lands on the body, they have to start over from the top.
  4. 4. Which statement about live regions is correct?

    Screen readers watch an existing region for changes, so render the container first and change only its content. status is polite; alert is assertive and interrupts.
  5. 5. What does a roving tabindex do in a group such as tabs or a toolbar?

    Only one item is in the Tab order, so Tab passes the group in one press, and arrow keys move focus between items. This matches native widgets.

Summary

  • Accessibility in React is accessibility in HTML: choose semantic elements first (button, a, headings, landmarks, lists, tables).
  • Give every control an accessible name: a visible <label htmlFor> with ids from useId, aria-label for icon buttons, alt for images, aria-describedby for hints.
  • You manage focus yourself in an app: move it into what opens, return it to the opener on close, keep a visible focus indicator.
  • ARIA supplements HTML; it never adds behavior. Prefer native elements and implement the keyboard model for custom widgets (roving tabindex, arrows, Home, End, Escape).
  • Announce dynamic changes with an always-rendered role="status" or role="alert" region.
  • Use skip links, ordered headings and page titles for navigation, and test with eslint-plugin-jsx-a11y, axe, a keyboard and a screen reader.

Next: Animation and Transitions