Focus Management in Single-Page Apps: A WCAG Guide

Focus Management in Single-Page Apps: A WCAG Guide

Multi-page apps get focus management for free; single-page apps do not. Route-change restoration in React and Next.js, modal focus trap with inert and <dialog>, and the WCAG 2.2 Focus Not Obscured rules.

Multi-page apps get focus management for free; single-page apps do not. This guide covers visible focus under SC 2.4.7, route-change focus restoration in React and Next.js, the modal focus trap with the modern inert attribute and <dialog> element, the new WCAG 2.2 Focus Not Obscured criteria (SC 2.4.11 / 2.4.12) that catch sticky-header overlap, and the framework-specific patterns that ship to production.

Why focus management is the load-bearing accessibility surface in SPAs

Multi-page applications get focus management for free. Every navigation is a full reload — focus resets to the document root, the screen reader announces the new page title, and the keyboard user starts at the top of fresh content. The browser does this automatically, and has since the early web.

Single-page applications break that contract. After a route change, the visible page has changed entirely, but focus stays on the link that triggered navigation. Screen readers continue reading from the old position. Keyboard users press Tab and end up somewhere unexpected — sometimes back at the previous page's footer, sometimes at the top of the new page, sometimes nowhere at all. Without explicit focus management, route changes can go unannounced to screen reader users and leave keyboard focus in the wrong place.

Modal-heavy SPAs add a second failure mode. Focus drifts into background content while the modal is visually open. Or focus fails to return to the trigger on close, leaving the keyboard user stranded at the document root. Both bugs are invisible to mouse users — and devastating to keyboard and screen reader users.

The asymmetry matters: SPA focus bugs are easy to miss in design reviews, manual QA by sighted users, and automated visual regression tests. They appear in accessibility audits and in user reports from people who already had a hard day. Focus management is a contained piece of accessibility work for a SPA team: the patterns are well documented, and the checklist at the end of this guide shows how to find these bugs with a keyboard.

Visible focus — what passes SC 2.4.7 and what 2.4.13 adds

SC 2.4.7 Focus Visible at Level AA requires that any keyboard-operable user interface have a mode of operation where the keyboard focus indicator is visible. The criterion does not specify thickness or contrast — those are quantified in the new WCAG 2.2 SC 2.4.13.

A frequent SC 2.4.7 failure is removing the default browser outline (outline: none) without a replacement. The pattern shows up in CSS resets, design system base styles, and component libraries that prioritize the visual look of the unfocused state. The fix is to suppress the outline only where the browser decides focus does not need to be shown — such as a mouse click on a button — using the :focus-visible pseudo-class:

css
/* Wrong: removes focus indicator entirely. */
button:focus { outline: none; }

/* Right: shows focus on keyboard; browsers generally hide it when a button is clicked with a mouse. */
button:focus-visible {
  outline: 2px solid var(--focus-ring);
  outline-offset: 2px;
}
button:focus:not(:focus-visible) { outline: none; }

The :focus-visible pseudo-class is the modern way to show focus only when the browser's heuristics decide it should be evident — on keyboard focus, but generally not when a button is clicked with a mouse (a text field that takes typed input still shows it when clicked). It is supported in every major browser as of 2022, and the historical pattern of outline: none followed by hand-rolled JavaScript focus-detection has been obsoleted.

A custom focus ring must be visible against every background it can appear on. One way to meet this is a focus token reserved exclusively for the indicator, with sufficient outline-offset so the ring reads as outside the element rather than absorbing into it. SC 1.4.11 Non-text Contrast requires the indicator to reach 3:1 against the colors next to it, so a focus token that just adopts the brand primary color can fail on light surfaces.

SC 2.4.13 Focus Appearance, new in WCAG 2.2 at Level AAA, adds quantitative requirements: when the keyboard focus indicator is visible, an area of it must be at least as large as the area of a 2 CSS pixel thick perimeter of the unfocused component or sub-component, and must have a contrast ratio of at least 3:1 between the same pixels in the focused and unfocused states. It does not apply when the indicator is determined by the user agent and cannot be adjusted by the author, or when neither the indicator nor its background color is modified by the author. A solid outline at least 2 CSS pixels thick is the simplest way to meet the size requirement (it still needs the 3:1 change between focused and unfocused states), but it is not the only shape that passes. This is appropriate as a design system aspiration on focus tokens but is not required at AA. SC 2.4.13 is AAA, not AA, and W3C itself does not recommend requiring Level AAA as a general policy for entire sites.

Focus on route change — the SPA-specific job

After a route change, focus should move somewhere predictable. WCAG does not name a destination; two options are the new page's primary heading or a skip-to-main-content target. Without explicit movement, screen reader users hear the old page's content after navigation while the visible page has changed entirely.

The Next.js App Router pattern uses usePathname and a useEffect that fires on every route change:

tsx
'use client'
import { useEffect, useRef } from 'react'
import { usePathname } from 'next/navigation'

export function PageHeading({ children }: { children: React.ReactNode }) {
  const ref = useRef<HTMLHeadingElement>(null)
  const pathname = usePathname()
  useEffect(() => {
    ref.current?.focus()
  }, [pathname])
  return (
    <h1 ref={ref} tabIndex={-1}>
      {children}
    </h1>
  )
}

The destination heading needs tabIndex={-1} because headings are not natively focusable. Next.js already ships a route announcer that reads the new page's document.title (falling back to the <h1>, then the URL) after client-side transitions, so in a Next.js app the job is to give every page a unique, descriptive title rather than to add a second live region. In routers without a built-in announcer, pair the focus move with an aria-live="polite" region that announces the new page title:

tsx
// React Router example — swap in your router's pathname source
import { useLocation } from 'react-router-dom'
import { useEffect, useState } from 'react'

export function RouteAnnouncer({ getTitle }: { getTitle: (pathname: string) => string }) {
  const { pathname } = useLocation()
  const [message, setMessage] = useState('')
  useEffect(() => {
    setMessage(`Navigated to ${getTitle(pathname)}`)
  }, [pathname, getTitle])
  return (
    <div role="status" aria-live="polite" className="sr-only">
      {message}
    </div>
  )
}

React Router v6 does not include focus restoration. The pattern is a top-level useEffect on useLocation that moves focus to a known target:

tsx
import { useLocation } from 'react-router-dom'
import { useEffect, useRef } from 'react'

export function PageHeading({ children }) {
  const ref = useRef(null)
  const location = useLocation()
  useEffect(() => {
    ref.current?.focus()
  }, [location.pathname])
  return <h1 ref={ref} tabIndex={-1}>{children}</h1>
}

In Vue Router, a global afterEach hook can programmatically focus a known element after each route transition.

The timing trap to watch for: if focus is moved from the click handler, it runs before the new route has rendered — and, with view transitions enabled, before the transition finishes. The mitigation is to defer the focus move into the useEffect that runs after the route has actually changed, not to call focus() directly from the click handler.

Modal focus trap and the inert attribute

The modal pattern has four contract points: focus moves into the modal on open, traps inside while open, returns to the trigger on close (unless the trigger no longer exists or the workflow makes another element a more logical destination), Escape closes.

The traditional implementation was manual — listen for Tab and Shift+Tab events, check if focus would leave the modal, intercept and redirect. Libraries like focus-trap and focus-trap-react handle this. They still work, and for codebases that target older browsers they remain necessary.

The modern implementation uses the inert attribute to mark every sibling of the modal as inert, removing them from the tab order and the accessibility tree in one declarative move:

html
<body>
  <header inert>...</header>
  <main inert>...</main>
  <footer inert>...</footer>
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-heading">
    <h2 id="modal-heading">Confirm changes</h2>
    <button>Cancel</button>
    <button>Confirm</button>
  </div>
</body>

inert is supported in all major browsers as of 2023. It removes its subtree from focus, hit-testing, and the accessibility tree, which is exactly the semantics a modal needs. Importantly, inert is different from aria-hidden — aria-hidden removes content from the accessibility tree but does not block focus, so a focusable element inside an aria-hidden ancestor can still receive keyboard focus. WAI-ARIA 1.2 includes the element that currently has focus in the accessibility tree even when it or an ancestor has aria-hidden="true", but the W3C's Using ARIA guidance (now a discontinued draft) warns that a focusable element hidden this way leaves some users focusing on "nothing".

Better still, the native <dialog> element handles inert internally when opened with showModal(). For many modal use cases, <dialog> plus a small CSS pass replaces the entire role="dialog" + custom focus-trap library + manual aria-modal stack:

html
<dialog id="confirm-dialog">
  <h2>Confirm changes</h2>
  <form method="dialog">
    <button value="cancel">Cancel</button>
    <button value="confirm">Confirm</button>
  </form>
</dialog>
<button id="open-trigger" type="button">Confirm changes…</button>
<script>
  const dialog = document.getElementById('confirm-dialog')
  document.getElementById('open-trigger').addEventListener('click', () => {
    dialog.showModal()
  })
</script>

showModal() opens the dialog, moves focus into it (to the dialog or a descendant carrying autofocus; otherwise to the first sequentially focusable element inside; otherwise to the dialog itself), marks the rest of the document inert, and binds Escape to close — without any additional library code. For React, libraries like Radix UI and React Aria Components provide accessible dialog components, though they implement their own role="dialog" element and focus containment rather than wrapping the native <dialog>.

WCAG 2.2 Focus Not Obscured — the new conformance surface

WCAG 2.2 added two criteria targeting a specific bug pattern: focus moves to an element that is hidden behind sticky content.

SC 2.4.11 Focus Not Obscured (Minimum) at Level AA says when an element receives keyboard focus, it must not be entirely hidden by author-created content. Sticky headers, cookie banners, chat widgets, and bottom-pinned promo bars are the typical violators. A common scenario: a long form on a page with a sticky header. The user Tabs from one field to the next, scrolling brings the focused field up to the top of the viewport, and the sticky header covers it.

SC 2.4.12 Focus Not Obscured (Enhanced) at Level AAA tightens the rule — the focused element must not be obscured at all, even partially. Again, W3C does not recommend requiring AAA as a general policy for entire sites.

One sufficient technique for both (W3C technique C43) is scroll-padding-top on the root scroll container, sized to match the height of the sticky element. For sticky banners, the 2.4.11 Understanding document also lists making the banner modal, so it must be dismissed before the user moves through the page; notifications that need no user action could also meet it by closing when they lose focus. The scroll-padding-top approach looks like this:

css
/* Reserve 64px at the top of the viewport for the sticky header,
   so focus moves that scroll the page stop below it. */
html { scroll-padding-top: 64px; }

/* Per-element scroll-margin works as an alternative on individual
   focusable targets when the sticky height varies by route. */
.section-target { scroll-margin-top: 80px; }

scroll-padding-top reserves space at the top of the scroll viewport. When focus moves to an anchor or a programmatically scrolled target, the browser scrolls so the focused element sits below the reserved space — clear of the sticky header.

SC 2.4.11 is written about keyboard focus — Tab, programmatic focus moves, anchor-link navigation — and at Level AA it fails only when the focused component is entirely hidden; partial overlap is a 2.4.12 (AAA) concern. This is important for designers who hear "focus must not be obscured" and worry that every UI element must be visible at all times — that is not what the criterion says.

Focus management in framework-specific patterns

Every framework has its own focus management quirks beyond the route-change pattern.

In Next.js App Router, a dependable pattern is to move focus inside a useEffect keyed on usePathname(), never inside the click handler, and never inside the <Link> component itself. If view transitions are enabled, test the focus move with the actual transition timing.

In React Router v6, focus restoration is not built in. The top-level useEffect on useLocation is the standard pattern. As of Oct 2026, the React Router v6 documentation (6.30.6) does not list a skip-link component, so skip links are left to the app.

Many modal-related accessibility regressions live in component-level focus handling. Every reusable component that captures focus on render must restore focus on unmount. A modal that takes focus on open but does not record the trigger element when it opens leaves no way to restore correctly on close. The pattern:

tsx
function Modal({ open, onClose, children }) {
  const triggerRef = useRef<HTMLElement | null>(null)
  const dialogRef = useRef<HTMLDialogElement>(null)

  useEffect(() => {
    if (open) {
      triggerRef.current = document.activeElement as HTMLElement
      dialogRef.current?.showModal()
    } else {
      dialogRef.current?.close()
      triggerRef.current?.focus()
    }
  }, [open])

  return <dialog ref={dialogRef} onClose={onClose}>{children}</dialog>
}

Storybook's accessibility addon runs axe-core against every story and flags static problems, such as focusable elements inside aria-hidden, at the component level. As of Oct 2026, axe-core's rule list (which the addon runs) has no checks that move focus or test focus traps and restoration, so pair it with interaction tests or keyboard checks for those.

Common focus management bugs that ship to production

Five patterns come up again and again.

Focus is moved to a non-tabbable element (a <div> with tabindex="-1") and the user has no clear cue. The cursor is somewhere, but Tab does not work as expected. Move focus to a heading with tabindex="-1" so the next Tab moves to the first interactive element after the heading.

Focus restoration after modal close goes to the wrong trigger. This happens when the trigger element re-renders during the modal being open — the captured ref points to a stale DOM node. Re-querying the trigger by stable selector on close, or recording the trigger as a stable string ID rather than a DOM ref, fixes it.

Skip link is announced but focus does not actually move. The target lacks tabindex="-1" and is not natively focusable, so focus itself never lands on it — current browsers only move the Tab starting point. Giving the target tabindex="-1" makes focus land on it explicitly.

Focus moves during a CSS transition and the visible focus indicator appears mid-animation. The fix is either disabling transitions on focus, or moving focus after the transition ends via transitionend event.

Focus moves on every state update because the focus-restore logic depends on a constantly-changing dependency. The symptom is keyboard users feeling "thrown" to a heading randomly. Audit the dependency array on every focus-related useEffect — only pathname and explicit triggers should appear.

Test priorities for your SPA

Focus management is component-level work. Most of the audit time should be spent on a representative sample of components, not every page.

  • Tab through every primary route after navigation — focus is on the new page heading or skip target, not stuck at the last link
  • Open and close every modal with the keyboard — Escape closes, focus returns to the trigger (unless it no longer exists or the workflow calls for another element), no focus leak to background
  • Test sticky headers, cookie banners, and chat widgets — Tab through a long form and confirm no field is entirely hidden when it receives focus (SC 2.4.11)
  • Confirm :focus-visible is used so focus rings appear on keyboard focus but generally not when a button is clicked with a mouse (or that the design intentionally shows on click)
  • Run the WCAG 2.2 Focus Appearance check on the design token level — focus indicators meet the 2.4.13 area (a 2 CSS pixel perimeter equivalent) and 3:1 focused-versus-unfocused contrast everywhere they appear, unless a 2.4.13 exception applies (indicator set by the user agent and not adjustable, or indicator and its background not modified by the author)
  • Migrate any custom modal pattern using a focus-trap library to <dialog> + showModal() if the codebase supports it

Route-change focus restoration plus the inert modal contract covers much of what audits flag on focus.

Project Inquiry