Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

Route focus

A hook that moves focus to the page title after a client-side navigation, so keyboard and screen reader users start at the top of the new page instead of on a link that may be gone. It renders nothing. It does nothing on the first load, when only the hash changes, or while someone is typing in a field.

Package
@kvirn-ui/react
Testing
Automated. Core 0 of 3, Release 0 of 3

When to use it#

  • Use it in a single-page app, where following a link changes the page without loading it again. Without it focus (the part of the page the keyboard is acting on) stays on the link, which may be gone.
  • Call it once, in the layout that holds every page, with the router’s location as the key: the path and the search, never the hash.
  • Give each page one h1 inside that layout. That is the element that gets focus.
  • Not for the first load, or a link to a section on the same page: it does nothing there. To jump past the header, use a SkipLink.
  • Not for a step in a form on one page: use the moveOn option of Focus.

Example#

Welcome

This is the start page.

Information: Implement like this

In Next.js, build the key from the pathname and the search in a client wrapper in the root layout. Next.js announces routes itself, so leave announce off.

'use client'
import { useRouteFocus } from '@kvirn-ui/react'
import { usePathname, useSearchParams } from 'next/navigation'
import { useRef } from 'react'

export function PageShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const search = useSearchParams().toString()
  const mainRef = useRef<HTMLElement>(null)
  useRouteFocus({ key: search === '' ? pathname : `${pathname}?${search}`, containerRef: mainRef })
  return <main ref={mainRef}>{children}</main>
}

Use cases#

A link to a section on the same page

Jumping to a section isn’t a new page, so focus should stay where it is. Leave the hash out of the key and the hook ignores it. Press “To services” and focus moves to the title; press “Jump to the details” and it stays on the button.

Welcome

This is the start page.

Props in this example:

  • key on useRouteFocus

Information: Implement like this

In TanStack Router, build the key from the path and the search, as below. If your router does not announce route changes, set announce: the page’s title is then also said in the live region. Update document.title before the key changes.

function Root() {
  const key = useRouterState({
    select: (state) => state.location.pathname + state.location.searchStr,
  })
  const mainRef = useRef<HTMLElement>(null)
  useRouteFocus({ key, containerRef: mainRef, announce: true })
  return <main ref={mainRef}><Outlet /></main>
}

A search that changes the address as you type

Some pages put the search in the address, so a result can be shared. Every keystroke then changes the key. The hook never takes focus from a text field, so the cursor stays where the visitor is typing.

Search our services

The address is now /search

Props in this example:

  • key on useRouteFocus

A router that doesn’t say the new page aloud

With announce on, a screen reader user also hears that the page changed, in your own words if you pass messages. Use it only where the router has no announcer of its own. Press “To services” and read the line below.

Welcome

This is the start page.

Props in this example:

Warning: Don't forget

Give every page a title that names it, and set it before the key changes. The hook says the title but doesn’t set it (2.4.2 Page Titled).

Accessibility#

What it does for you#

  • APG pattern: none. It is not a widget. It applies the W3C technique of moving focus to the new page title on a single-page navigation (WCAG technique G110 is the redirect-based alternative; technique ARIA22 covers the optional status message).
  • Deviations: none.
  • Native elements used: the consumer's own <h1>, made temporarily focusable with tabindex="-1".

A client-side navigation does not reload the page, so focus stays on the clicked link (which may be gone) and a screen reader says nothing (2.4.3 Focus Order, level A; 4.1.3 Status Messages, level AA). useRouteFocus moves focus to the new page's title once per navigation. It is a hook only: it renders nothing and returns nothing to spread.

PartElement / roleARIANotes
The titlethe consumer's <h1> → headingnonetabindex="-1" is added just before focus when the element has no tabindex, and removed on blur. An element that already has a tabindex keeps it. The heading level and role are never changed
the hooknonenoneNo aria-live of its own. With announce on, the text goes through the shared Announcer

What you need to do#

  • Pass a stable key. Path plus search from your router, never the hash. Call the hook once, in the layout that holds the page.
  • Render one <h1> per page inside the container. Without it the hook warns and moves nothing.
  • Keep scroll-padding-top above a sticky header so the focused title is not covered (2.4.11 Focus Not Obscured (Minimum), level AA).
  • Scroll restoration is the router's. Under 'manual' the hook also moves focus on Back and Forward.
  • Next.js already announces routes. Leave announce off there. With a router that has no announcer of its own, turn announce on, or a screen reader user hears nothing about the new page after Back or Forward.
  • Give every route a document.title that names the page, and set it before the key changes (2.4.2 Page Titled (A)). The hook neither sets nor checks it.

Warning: Don't forget

Keep scroll-padding-top above a sticky header, so it doesn’t cover the title that gets focus (2.4.11 Focus Not Obscured (Minimum)).

Visual and modes#

  • Focus indicator: the default theme draws its focus ring on the focused h1, and uses the system's highlight colour in forced colours (Windows contrast themes). The hook ships no CSS and sets no data attribute.
  • forced-colors behaviour, reduced-motion and reflow: the hook adds no style, so nothing changes. It never animates scroll.

Focus management#

  • Initial focus: not moved on the first load.
  • Moves to the h1 (or selector) inside containerRef (the document when absent) when key changes. key is the pathname plus the search, never the hash, so a hash-only change does nothing (route focus: with a real history › a hash-only change is skipped, and focus stays on the link).
  • Skipped: the first load, an unchanged key, Back or Forward while history.scrollRestoration is 'auto' (the browser restores scroll, not focus; see below), a text field or textarea having focus (the user is typing), and a missing target (a development warning route-focus-target-missing, nothing else).
  • A fragment link (a skip link, a table of contents) fires popstate too but leaves the key alone, so it never marks the next navigation as a Back or Forward: the hook compares the address recorded at popstate with the location when the key changes, never with the key itself, so a basePath or a re-encoded search in the key cannot defeat it (route focus: with a real history › a hash link, then a pushed path, still focuses the title, › a hash link, then a pushed path, still announces).
  • Back or Forward under 'auto': the browser restores scroll position only, not focus, so focus stays on body. The skip is kept on purpose: a restored scroll position is the reading position the user expects, and a focus jump to the title would scroll it away. With announce on, the navigation is still announced (use-route-focus.test.tsx › route focus: with a real history › Back under automatic scroll restoration moves no focus, but still announces when announce is on). It needs the AT run.
  • Trap: no. Restore to: not applicable. The next Tab continues from the title.
  • Never obscured by: the title scrolls into view (preventScroll: false). Pair it with scroll-padding-top for a sticky header (2.4.11 Focus Not Obscured (Minimum), level AA).
  • The ring shows under :focus-visible only (the maintainer's decision). The browser does not show it on a pointer-initiated focus(). The default theme draws it with a rule that your own CSS can override.

Information: Did you know?

On Back and Forward the hook leaves focus alone while the browser restores the scroll position, so someone going back does not land on the title. The contract lists this as still to be confirmed. With history.scrollRestoration set to manual the hook moves focus then too.

WCAG success criteria#

  • 2.4.3 Focus Order (A): focus lands on the title and Tab continues from it (keyboard › Tab after a navigation continues after the title).
  • 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA): the title is focused and scrolled in. The ring is the default theme's.
  • 3.2.1 On Focus (A): no move on the first load, a hash change or while typing (route focus: when it moves › typing in a text field skips the move).
  • 4.1.3 Status Messages (AA): the optional announce through the Announcer.
  • Axe: no violations with the title focused (accessibility › no axe violations with the title focused).

Keyboard#

Focus
native
Selection follows focus
n/a
Arrows wrap
n/a
Shortcuts
none

Focus is moved programmatically, once per navigation, to a heading made temporarily focusable, then native tab order continues from it. The hook adds no Tab stop, handles no keys and never intercepts one.

KeyWhereWhat happens
Tabafter a navigationContinues after the focused h1, into the page's first stop
Test: use-route-focus.test.tsx › keyboard › Tab after a navigation continues after the title
Shift+Tabafter a navigationGoes back to the stop before the h1 (the header), not to the old link
Test: use-route-focus.test.tsx › keyboard › Shift+Tab after a navigation goes back to the stop before the title
Enteron the focused h1Not handled (not a control)
Test: use-route-focus.test.tsx › keyboard › the title is not a control and handles no keys

Announcements#

Route focus tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).

WhenWhat it saysMessage keyPoliteness
after the move, with announcerouteFocus.navigatedPolite
Back or Forward that moved no focus ('auto'), with announcerouteFocus.navigatedPolite

The text in all five languages

Change the text#

For your whole app, pass messages to KvirnProvider. For one Route focus, pass its messages prop.

<KvirnProvider messages={{ routeFocus: { navigated: '…' } }}>

Warning: Don't forget

Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.

What a screen reader reads#

State or actionRead aloudPolitenessTest
Back or Forward under 'auto', announce onNavigated to {title}, focus stayspoliteuse-route-focus.test.tsx › route focus: with a real history › Back under automatic scroll restoration reads the navigated message as polite and moves no focus

API reference#

import { useRouteFocus } from '@kvirn-ui/react'

useRouteFocus

Returns nothing: call it once, in the layout.

Options

PropTypeDefaultDescription
keystringRequiredThe router’s location as a string: the pathname plus the search, never the hash. Focus moves when it changes.
containerRefRefObject<Element | null>the documentWhere to look for the selector: the element that holds the page.
selectorstring'h1'The element to focus. If it has no tabindex of its own, it gets tabindex="-1" for as long as it has focus.
announcebooleanfalseAlso says “Navigated to {title}” in the shared live region, with document.title as the title, or the heading’s text when the title is empty. Leave it off where the router already announces routes.
messagesPartial<KvirnMessages['routeFocus']>–Overrides the message routeFocus.navigated for this call.

Strings

These are the default texts in @kvirn-ui/i18n.

For your whole app, pass messages to KvirnProvider. For one useRouteFocus, pass its messages prop.

routeFocus.navigated

Announced after a navigation when announce is on.

LanguageDefault text
SvenskaDu har kommit till {title}
SuomiSiirryit sivulle {title}
Norsk bokmålDu har kommet til {title}
Norsk nynorskDu har kome til {title}
EnglishNavigated to {title}

Known issues#

  • Back and Forward under scrollRestoration: 'auto' move no focus. After Back or Forward under scrollRestoration: 'auto', focus is not moved and stays on body, to keep the restored reading position. With announce off and no router announcer, a screen reader user hears nothing about the new page.

Testing#

The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.

AT + browser + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apassroute-focus.stories.tsx, every story, 4 themes (apps/storybook/src/components/focus/)
Markup and ARIA (roles, names, ids, states)passn/apassuse-route-focus.test.tsx › first load does not move focus or touch the title; expectNoA11yViolations
Keyboard contract rows (Vitest browser)passn/apass3 rows, each names a test (use-route-focus.test.tsx › keyboard › Tab after a navigation continues after the title)
Focus order and managementpassn/apassuse-route-focus.test.tsx asserts focus (toHaveFocus); first rule: keyboard › Tab after a navigation continues after the title
Display modes (forced colours, 320px reflow, text spacing, reduced motion)n/an/an/adraws nothing itself; the focus ring on the focused h1 is the theme's general focus rule
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending
Component-specific
Next.js announcer doubled or notpendingpendingpending