Skip to content
ClapelloNotes by Barath
ReactCh 17 · 4/6
Core6 min readUpdated

React / 97

Keyboard, focus and ARIA

TL;DR

Keep focus visible and in a sensible order, move it on purpose when modals open, reach for ARIA only when HTML can't do the job, and announce changes.

Make focus visible

Keyboard users need to see where they are. The browser draws a focus ring for you. The most common accessibility bug on the web is removing it:

Don't

Delete the ring

button:focus {
  outline: none;
}

Do

Style it for keyboard focus

button:focus-visible {
  outline: 3px solid darkorange;
  outline-offset: 2px;
}

:focus-visible matches when the browser decides the ring is useful: when focus came from the keyboard, but usually not after a mouse click. That's what designers who ask you to "remove the ugly outline" really want. In Tailwind: focus-visible:outline-2 focus-visible:outline-offset-2.

Tab order follows the DOM

Tab moves through focusable elements in source order. Keep your JSX in the order people read the page. If CSS moves things around visually (flex-direction: row-reverse, grid placement, order), focus will jump around the screen.

tabIndexEffectUse it for
0Joins the Tab order where it sits in the DOMA custom widget with no native element
-1Focusable only from code (ref.current.focus())Moving focus to a heading or a container
1 and upJumps ahead of everything elseNever. It scrambles the order

Move focus when the page changes

The biggest case is a modal: a dialog that blocks the page until you deal with it. It has four jobs with focus:

  1. 1 · open

    Focus moves in

    Focus jumps into the dialog, so keyboard and screen reader users land in it.
  2. 2 · inside

    Focus stays in

    Tab cycles inside the dialog. The page behind is inert: no focus, no clicks.
  3. 3 · Escape

    Easy way out

    Escape closes it, as well as a visible Close or Cancel button.
  4. 4 · close

    Focus goes back

    Focus returns to the button that opened it, so the user keeps their place.
A native <dialog> opened with showModal() does all four for you. A modal built from divs has to do every step in JavaScript.

The native <dialog> element, opened with showModal(), does all four. In React, open it from an effect, because showModal() is a DOM method:

ConfirmDialog.jsx
import { useEffect, useRef } from "react";
 
export function ConfirmDialog({ open, onClose }) {
  const ref = useRef(null);
 
  useEffect(() => {
    const dialog = ref.current;
    if (open && !dialog.open) dialog.showModal();
    if (!open && dialog.open) dialog.close();
  }, [open]);
 
  return (
    <dialog ref={ref} onClose={onClose} aria-labelledby="clear-title">
      <h2 id="clear-title">Clear your cart?</h2>
      <button type="button" onClick={onClose}>Cancel</button>
      <button type="button" onClick={onClose}>Clear</button>
    </dialog>
  );
}

onClose fires however it closes, including Escape, so the parent's open state stays in sync. aria-labelledby gives the dialog its name: "Clear your cart?, dialog". Watch focus move in a real one:

Where does focus go?

Try it
  1. focus log
  2. Nothing yet. Open the dialog.

Clear your cart?

This removes all 3 items. Try Tab a few times: focus stays in here.

Open the dialog with the keyboard (Tab to it, press Enter). Tab inside: focus can't escape to the page. Press Escape or Cancel, and focus lands back on the opener.

Two other moments to move focus yourself:

  • After a route change in a single-page app, nothing tells a screen reader that a new page arrived. Focus stays where it was, or drops to the page body if that element was removed. Focus the new page's <h1> (give it tabIndex={-1}) so reading starts at the top.
  • After deleting the focused item, focus vanishes with it. Move it to the next item, or to the list's heading.

ARIA: only when HTML can't

ARIA (Accessible Rich Internet Applications) is a set of attributes that change what assistive technology is told about an element. Its first rule: if a native HTML element does the job, use that instead. ARIA changes only what's announced. role="button" adds no keyboard support, and a wrong role is worse than none.

The ones you'll actually use:

AttributeUseExample
aria-labelNames a control that has no visible text<button aria-label="Close"> around an icon
aria-hidden="true"Hides decoration from screen readersthe icon inside that button
aria-expandedSays whether a toggle's panel is open<button aria-expanded={isOpen}>Filters</button>
aria-describedbyLinks extra help or an error to a field<input aria-describedby="email-error">
aria-current="page"Marks the current link in a navReact Router's <NavLink> adds it for you

Announce changes with live regions

When something changes away from the user's focus ("Added to cart", "3 results"), sighted users see it but screen reader users don't. A live region is an element whose content changes get read out:

CartButton.jsx
import { useState } from "react";
 
function CartButton() {
  const [count, setCount] = useState(0);
  return (
    <>
      <button type="button" onClick={() => setCount((c) => c + 1)}>Add to cart</button>
      <p role="status">{count > 0 ? `${count} items in cart` : ""}</p>
    </>
  );
}

role="status" is polite: it waits until the screen reader finishes speaking. role="alert" interrupts at once, so save it for errors that need immediate attention.

Test it yourself

  1. Put the mouse away

    Tab through the whole page. Can you see focus at every step? Reach and use everything? Escape every modal?
  2. Zoom to 200%

    Nothing should be cut off or overlap.
  3. Turn on a screen reader

    VoiceOver on macOS and iOS (Cmd+F5 on a Mac), NVDA on Windows (free), Narrator on Windows (Ctrl+Win+Enter), TalkBack on Android. Listen to one key flow, like adding to cart.
  4. Run an automated check

    Lighthouse's accessibility audit in Chrome DevTools, or the axe extension. They catch missing labels and low contrast, but not whether the page makes sense. Use them as well as the steps above, never instead of them.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.