Skip to content

Lesson 32 of 37React at scale

Accessible Components: Portals, Focus and ARIA

Build modals, tabs and live updates that work with a keyboard and a screen reader: portals, native dialog, useId, focus management and testing.

23 min read0/4 questions

A team ships a "Delete project?" modal built from a div with a dark overlay. It looks right. A keyboard user opens it, presses Tab, and focus walks out of the modal into the page behind it. A screen reader user hears nothing at all when it opens, because nothing told the reader that a dialog appeared. The audit before a big customer contract fails on that one component, and the fix touches every modal in the app. In the EU, the European Accessibility Act has applied to many consumer products and services since June 2025, so this is now a legal and sales problem, not only a nice-to-have. This lesson is about the React-specific parts of getting it right: portals, focus, ids, keyboard patterns and how to test them.

What a custom widget owes its users

You saw in Accessibility basics that native HTML gives you most things for free. A <button> is focusable, fires on Enter and Space, and is announced as a button. The moment you build something the browser has no element for, like tabs or a combobox, you take over that job. Every interactive widget owes the user five things:

NeedWhat it meansWho provides it for a <button>
RoleWhat it is: dialog, tab, menu itemThe browser
NameWhat it is called: "Delete project"Its text content
StateSelected, expanded, checked, invaliddisabled, aria-pressed
KeyboardWhich keys do whatThe browser
FocusWhere focus goes when things open, close or vanishNobody. This one is always yours.

The last row is where React apps fail most. React re-renders DOM freely. When a node that had focus disappears, the browser drops focus to <body>, and a keyboard user is thrown back to the top of the page. Nothing in React prevents that. You have to decide where focus goes.

Portals: rendering outside the box

A dropdown inside a card with overflow: hidden gets clipped. A modal inside a parent with transform or a low z-index can never sit above the header, because it is trapped in that parent's stacking context. The classic React answer is a portal: createPortal(children, domNode) renders children into a different DOM node, usually document.body, while they stay where they are in the React tree.

That last part is the surprise. A portal moves the DOM, not the component. Context still flows into portal children, and React events bubble through the React tree, not the DOM tree. Click the menu item below and watch the console.

ReactPortalBubbling.tsx
import { useState } from "react";import { createPortal } from "react-dom"; function Menu({ onPick }: { onPick: (item: string) => void }) { return createPortal( <div style={{ position: "fixed", top: 60, left: 24, padding: 8, background: "#fff", border: "1px solid #999" }}> <button onClick={() => onPick("Rename")}>Rename</button> </div>, document.body, );} export default function App() { const [open, setOpen] = useState(false); return ( <div onClick={() => console.log("card clicked: opening details page")} style={{ overflow: "hidden", height: 40, padding: 8, border: "1px solid #ccc" }} > Project card{" "} <button onClick={(e) => { e.stopPropagation(); setOpen(!open); }} > Actions </button> {open && <Menu onPick={(item) => console.log("menu picked:", item)} />} </div> );}

The menu's DOM lives at the end of <body>, far from the card. The click still reaches the card's onClick, because the card is the menu's parent in React. That is useful (a dialog's events reach its owner, context just works) and also a classic bug: "clicking inside the modal triggers the row it was opened from". Stop propagation at the portal's root, or put row-level click handlers on a button instead of the whole row.

Predict the outputJavaScript

The user opens the menu and clicks Rename. What is logged, in order?

// Card: <div onClick={() => log("card")}>
//   Menu rendered with createPortal(..., document.body)
//     <button onClick={() => log("menu")}>Rename</button>
// The Rename click handler does not call stopPropagation.
Need a nudge? Hints walk you through it.

Portals are less necessary than they used to be. The browser now has a top layer: elements shown with dialog.showModal() or the popover attribute render above everything else regardless of z-index, overflow or transform on their ancestors. You still reach for a portal for a toast region or for code that must support a browser without these features, but for modals and popovers the native route solves stacking and accessibility together.

Native dialog first

<dialog> opened with showModal() does a lot of the hard work for you:

  • It renders in the top layer with a ::backdrop you can style.
  • Everything outside the dialog becomes inert: not clickable, not focusable, hidden from screen readers.
  • Focus moves into the dialog, to the first focusable element unless one has autofocus.
  • Escape fires a cancel event and then closes it, firing close.
  • When it closes, current browsers return focus to the element that was focused before it opened.

React does not have a declarative "modal open" prop for it. Setting the open attribute shows a non-modal dialog, which skips the inert background. So you call showModal() and close() from an effect, and listen to onClose so that a close you did not start (Escape) still sets your state back to closed. onCancel fires only for Escape, which is handy if you want to know how it was dismissed.

ReactConfirmDialog.tsx
import { useEffect, useId, useRef, useState } from "react"; function ConfirmDialog({ open, title, onClose, onDismiss, children }: { open: boolean; title: string; onClose: () => void; onDismiss: () => void; children: React.ReactNode;}) { const ref = useRef<HTMLDialogElement>(null); const titleId = useId(); useEffect(() => { const dialog = ref.current; if (!dialog) return; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} aria-labelledby={titleId} onCancel={onDismiss} onClose={onClose} style={{ maxWidth: 320 }}> <h2 id={titleId} style={{ marginTop: 0, fontSize: 18 }}>{title}</h2> {children} </dialog> );} export default function App() { const [open, setOpen] = useState(false); const [result, setResult] = useState("Nothing yet"); function choose(outcome: string) { setResult(outcome); setOpen(false); } return ( <div> <button onClick={() => setOpen(true)}>Delete project</button> <p role="status">Last result: {result}</p> <ConfirmDialog open={open} title="Delete this project?" onDismiss={() => setResult("dismissed with Escape")} onClose={() => setOpen(false)} > <p>This removes 14 files. You cannot undo it.</p> <div style={{ display: "flex", gap: 8 }}> <button onClick={() => choose("cancelled")}>Cancel</button> <button onClick={() => choose("deleted")}>Delete</button> </div> </ConfirmDialog> </div> );}

Open it with the keyboard, press Tab a few times (focus stays inside), then press Escape. Focus lands back on "Delete project". Notice that Cancel comes first, so it receives focus on open. For a destructive action, the safe choice should be the one a stray Enter hits.

Focus through a modal's life
UserTriggerDialogPageEnter on Delete projectshowModal()rest of page is inertEscapefocus returns

Focus is on the trigger. The browser remembers it.

1/5

The popover attribute is the non-modal sibling: menus, tooltips-with-content, small pickers. popover="auto" gives you top layer rendering and light dismiss (Escape or a click outside closes it), and React 19 accepts popoverTarget on a button to wire the toggle without any state. A popover does not make the page inert and does not trap focus, which is correct for non-modal UI. You still add the ARIA pattern for what it contains, such as aria-expanded on a menu button.

When you build it yourself

Sometimes you cannot use <dialog>, for example inside an old design system. Then you own the whole list: move focus in on open, keep Tab inside (a focus trap), close on Escape, make the background unreachable, lock scroll, and return focus on close. For the background, the inert attribute is the modern tool. React 19 treats inert as a proper boolean prop, so <main inert={isModalOpen}> works. (In React 18 you had to pass an empty string, which is why old code looks odd.) Setting aria-hidden on the background hides it from screen readers but leaves it focusable, which is worse than nothing.

Quick check
A teammate opens a modal by rendering <dialog open> from state. Keyboard users report they can still Tab to the page behind it. Why?
Need a nudge? A hint rules out a wrong answer.

Wiring labels and descriptions with useId

Accessible names and descriptions are wired with ids: aria-labelledby points at the dialog title, aria-describedby points at hint or error text, <label htmlFor> points at an input. In a reusable component you cannot hardcode id="email", because two instances on one page would clash. And you cannot use Math.random() or a module counter, because the server and the client would generate different values and hydration would fail.

useId gives each component instance an id that is unique on the page and identical on the server and the client, because it is derived from the component's position in the tree. Call it once and add suffixes for related elements.

components/TextField.tsx
import { useId } from "react";
 
export function TextField({ label, hint, error, ...inputProps }: {
  label: string;
  hint?: string;
  error?: string;
} & React.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>
      <label htmlFor={id}>{label}</label>
      <input id={id} aria-describedby={describedBy} aria-invalid={error ? true : undefined} {...inputProps} />
      {hint && <p id={hintId}>{hint}</p>}
      {error && <p id={errorId}>{error}</p>}
    </div>
  );
}

Two rules. Do not use useId for list keys; keys come from your data. And do not parse or style by the generated string. Its format has changed between React versions and is an implementation detail.

Moving focus after things happen

Focus management is mostly about the moments when the focused element disappears or the context changes:

  • Deleting an item. The Delete button you pressed no longer exists. Move focus to the next item's button, the previous one if it was the last, or the list heading if the list is empty.
  • Closing a custom panel. Return focus to whatever opened it.
  • Client-side navigation. A full page load resets focus to the top; a client route change does not. Move focus to the new page's <h1> (with tabIndex={-1} so it can receive focus) or use your router's built-in handling. Client-side routing covers this in detail.
  • An async result. "Saved", "3 results found", "Upload failed". These need a live region, not a focus move.

A live region is an element whose changes the screen reader announces. role="status" is polite (announced when the reader is idle); role="alert" is assertive and interrupts, so keep it for real errors. The region must already be in the DOM before its text changes. Rendering a brand-new <div role="status">Saved</div> at the same moment as its content is often not announced at all.

Try deleting items with the keyboard below, with and without focus management. Watch the console to see where focus ends up.

ReactFocusAfterDelete.tsx
import { useRef, useState } from "react";import { flushSync } from "react-dom"; const START = ["Invoice 1042", "Invoice 1043", "Invoice 1044"]; export default function App() { const [items, setItems] = useState(START); const [message, setMessage] = useState(""); const [manageFocus, setManageFocus] = useState(true); const headingRef = useRef<HTMLHeadingElement>(null); const buttons = useRef(new Map<string, HTMLButtonElement>()); function remove(index: number) { const name = items[index]; const next = items.filter((_, i) => i !== index); flushSync(() => { setItems(next); setMessage(`${name} deleted. ${next.length} left.`); }); if (manageFocus) { const target = next[index] ?? next[index - 1]; if (target) buttons.current.get(target)?.focus(); else headingRef.current?.focus(); } const el = document.activeElement; console.log("focus is on:", el?.getAttribute("aria-label") ?? el?.tagName); } return ( <div> <label> <input type="checkbox" checked={manageFocus} onChange={(e) => setManageFocus(e.target.checked)} /> Manage focus </label> <h3 ref={headingRef} tabIndex={-1}>Invoices</h3> <ul> {items.map((item, i) => ( <li key={item}> {item}{" "} <button aria-label={`Delete ${item}`} ref={(node) => { if (node) buttons.current.set(item, node); return () => { buttons.current.delete(item); }; }} onClick={() => remove(i)} > Delete </button> </li> ))} </ul> <p role="status">{message}</p> <button onClick={() => setItems(START)}>Reset</button> </div> );}

flushSync forces React to commit the update before the next line runs, so the next button's DOM is in its final state when you call focus(). Use it sparingly; it opts out of batching. The alternative is to store "what should be focused" in state and focus it in an effect. The ref callback with a cleanup (new in React 19) keeps the map of buttons accurate as items come and go.

Keyboard patterns and roving tabindex

You do not invent keyboard behavior. The WAI-ARIA Authoring Practices Guide (APG) documents the expected keys for each widget, and screen reader users rely on them. A few you will meet at work:

Match the pairs0/4 matched

Match each widget to its expected keyboard behavior from the APG.

Choose an item, then its match on the other side.

The technique behind "one Tab stop, arrows inside" is roving tabindex: the active item has tabIndex={0}, every other item has tabIndex={-1}, and arrow keys move both the selection and focus. Press Tab into the tabs below, then use the arrows, Home and End.

ReactRovingTabs.tsx
import { useId, useRef, useState } from "react"; const TABS = [ { label: "Overview", body: "Three open issues, last deploy two hours ago." }, { label: "Activity", body: "Sam merged a pull request. Ana opened an issue." }, { label: "Settings", body: "Visibility: private. Default branch: main." },]; export default function App() { const [selected, setSelected] = useState(0); const tabs = useRef<(HTMLButtonElement | null)[]>([]); const id = useId(); function onKeyDown(e: React.KeyboardEvent) { const last = TABS.length - 1; const moves: Record<string, number> = { ArrowRight: selected === last ? 0 : selected + 1, ArrowLeft: selected === 0 ? last : selected - 1, Home: 0, End: last, }; const next = moves[e.key]; if (next === undefined) return; e.preventDefault(); setSelected(next); tabs.current[next]?.focus(); } return ( <div> <button>Before the tabs</button> <div role="tablist" aria-label="Project" onKeyDown={onKeyDown} style={{ display: "flex", gap: 4, margin: "12px 0" }}> {TABS.map((tab, i) => ( <button key={tab.label} ref={(node) => { tabs.current[i] = node; }} role="tab" id={`${id}-tab-${i}`} aria-selected={i === selected} aria-controls={`${id}-panel-${i}`} tabIndex={i === selected ? 0 : -1} onClick={() => setSelected(i)} style={{ fontWeight: i === selected ? 700 : 400 }} > {tab.label} </button> ))} </div> {TABS.map((tab, i) => ( <div key={tab.label} role="tabpanel" id={`${id}-panel-${i}`} aria-labelledby={`${id}-tab-${i}`} hidden={i !== selected} tabIndex={0}> {tab.body} </div> ))} <button style={{ marginTop: 12 }}>After the tabs</button> </div> );}

Tab from "Before the tabs" lands on the selected tab, and the next Tab goes to the panel, not to the other tabs. One warning: role="menu" is for application-style menus with arrow-key navigation, like a desktop app's File menu. A site's navigation links are just a <nav> with a list of links. Adding role="menu" there changes how screen readers behave and makes it harder to use.

Headless libraries: why teams buy instead of build

Tabs and a disclosure are reasonable to build yourself. A combobox, a date picker, nested menus with submenus, or a select that works with VoiceOver on iOS are not. The edge cases took library authors years: pointer versus keyboard focus, scroll locking without layout shift, nested dialogs, typeahead, right-to-left arrow keys, touch screen readers.

Headless libraries give you that behavior and ARIA wiring with no styles, so your design system stays yours:

  • Radix Primitives: compound components (Dialog.Root, Dialog.Trigger, Dialog.Content), and the original base for shadcn/ui.
  • Base UI: from people behind Radix, Floating UI and Material UI, with a render prop for swapping the rendered element. shadcn/ui can now be set up on it too.
  • React Aria (Adobe): hooks and components with very deep internationalization and screen reader testing.

The trade-off is a dependency and its API in your public components. Component API design looks at how to wrap one without leaking it everywhere. The senior move is to wrap the library in your own Dialog or Select once, so a later swap touches one folder.

Testing accessibility

Three layers, each catching different things.

Query by role in component tests. Testing React showed getByRole. It doubles as an accessibility check: if getByRole("tab", { name: "Activity" }) cannot find your tab, a screen reader probably cannot either.

Tabs.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
 
test("arrow keys move between tabs", async () => {
  const user = userEvent.setup();
  render(<ProjectTabs />);
  await user.tab();
  expect(screen.getByRole("tab", { name: "Overview" })).toHaveFocus();
  await user.keyboard("{ArrowRight}");
  expect(screen.getByRole("tab", { name: "Activity" })).toHaveAttribute("aria-selected", "true");
});

Automated rules with axe. vitest-axe or jest-axe run the axe-core rules against rendered output, and @axe-core/playwright runs them against real pages in end-to-end tests:

e2e/a11y.spec.ts
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";
 
test("settings page has no detectable a11y violations", async ({ page }) => {
  await page.goto("/settings");
  const results = await new AxeBuilder({ page }).analyze();
  expect(results.violations).toEqual([]);
});

Manual checks. Automated tools find missing labels, bad contrast and invalid ARIA, but they cover only part of the guidelines. They cannot tell you that focus vanished after a delete or that the announcement made no sense. Before shipping a new widget, unplug the mouse and use it with the keyboard, then try it with VoiceOver (macOS, iOS) or NVDA (Windows) for two minutes.

Quick check
After saving a form, a toast says "Saved". Screen reader users never hear it. The toast is rendered as {saved && <div role="status">Saved</div>}. What is the most likely fix?
Need a nudge? A hint rules out a wrong answer.
Key terms
portal
createPortal(children, node) renders children into another DOM node. They stay in the React tree, so context and React events still flow through their React parents.
top layer
A browser layer above all page content, used by showModal() dialogs and popovers, unaffected by z-index, overflow or transforms of ancestors.
inert
An HTML attribute that makes a subtree unfocusable, unclickable and hidden from assistive tech. A boolean prop in React 19.
useId
A hook that returns an id unique on the page and identical on server and client, for wiring labels, descriptions and ARIA relationships.
live region
An element such as role="status" whose content changes are announced by screen readers. It must exist before its content changes.
roving tabindex
Keeping one item in a composite widget at tabIndex={0} and the rest at -1, moving focus between them with arrow keys.
headless library
A component library that supplies behavior, keyboard support and ARIA but no styling, such as Radix, Base UI or React Aria.