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
moveOnoption of Focus.
Example#
Welcome
This is the start page.
import { Button, Heading, useRouteFocus } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useRouteFocusTexts } from './texts.ts'
export function ChangePage() {
const { texts } = useRouteFocusTexts()
const [page, setPage] = useState<'start' | 'services'>('start')
const pageRef = useRef<HTMLDivElement>(null)
// The docs page already has an h1, so this example uses an h4. On your pages the default is h1.
useRouteFocus({ key: page, containerRef: pageRef, selector: 'h4' })
return (
<div>
<p>
<Button onClick={() => setPage('start')}>{texts.toStart}</Button>{' '}
<Button onClick={() => setPage('services')}>{texts.toServices}</Button>
</p>
<div ref={pageRef}>
<Heading as="h4">{texts[page].title}</Heading>
<p>{texts[page].body}</p>
</div>
</div>
)
}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.
import { Button, Heading, useRouteFocus } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useRouteFocusTexts } from './texts.ts'
export function HashChange() {
const { texts } = useRouteFocusTexts()
const [location, setLocation] = useState({ path: '/start', search: '', hash: '' })
const pageRef = useRef<HTMLDivElement>(null)
// The key is the path plus the search. The hash is left out, so a jump to a section moves nothing.
useRouteFocus({ key: location.path + location.search, containerRef: pageRef, selector: 'h4' })
return (
<div>
<p>
<Button onClick={() => setLocation({ path: '/services', search: '', hash: '' })}>
{texts.toServices}
</Button>{' '}
<Button onClick={() => setLocation({ ...location, hash: '#details' })}>
{texts.toDetails}
</Button>
</p>
<div ref={pageRef}>
<Heading as="h4">
{location.path === '/start' ? texts.start.title : texts.services.title}
</Heading>
<p>{location.path === '/start' ? texts.start.body : texts.services.body}</p>
{location.hash === '#details' && <p>{texts.details}</p>}
</div>
</div>
)
}Props in this example:
keyon 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
import { Field, Heading, TextInput, useRouteFocus } from '@kvirn-ui/react'
import { useRef, useState } from 'react'
import { useRouteFocusTexts } from './texts.ts'
export function SearchAsYouType() {
const { texts } = useRouteFocusTexts()
const [query, setQuery] = useState('')
const pageRef = useRef<HTMLDivElement>(null)
const address = query === '' ? '/search' : `/search?q=${encodeURIComponent(query)}`
// The search is part of the key, so every keystroke changes it. The hook leaves focus in the
// field while the visitor types.
useRouteFocus({ key: address, containerRef: pageRef, selector: 'h4' })
return (
<div ref={pageRef}>
<Heading as="h4">{texts.search.title}</Heading>
<Field.Root>
<Field.Label>{texts.search.label}</Field.Label>
<TextInput name="q" autoComplete="off" value={query} onValueChange={setQuery} />
</Field.Root>
<p>
{texts.search.address} <code>{address}</code>
</p>
</div>
)
}Props in this example:
keyon 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.
import { Button, Heading, useRouteFocus } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useRouteFocusTexts } from './texts.ts'
export function AnnouncedPage() {
const { texts } = useRouteFocusTexts()
const [page, setPage] = useState<'start' | 'services'>('start')
const [said, setSaid] = useState('')
const pageRef = useRef<HTMLDivElement>(null)
// Only for this docs page: put the page's own title back when the example goes away.
useEffect(() => {
const original = document.title
return () => {
document.title = original
}
}, [])
useRouteFocus({
key: page,
containerRef: pageRef,
selector: 'h4',
announce: true,
messages: { navigated: ({ title }) => texts.navigated(title) },
})
const goTo = (next: 'start' | 'services') => {
// The hook says document.title, so set it before the key changes.
document.title = texts[next].title
setSaid(texts.navigated(texts[next].title))
setPage(next)
}
return (
<div>
<p>
<Button onClick={() => goTo('start')}>{texts.toStart}</Button>{' '}
<Button onClick={() => goTo('services')}>{texts.toServices}</Button>
</p>
<div ref={pageRef}>
<Heading as="h4">{texts[page].title}</Heading>
<p>{texts[page].body}</p>
</div>
{said !== '' && (
<p>
{texts.saidAloud} {said}
</p>
)}
</div>
)
}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 withtabindex="-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.
| Part | Element / role | ARIA | Notes |
|---|---|---|---|
| The title | the consumer's <h1> → heading | none | tabindex="-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 hook | none | none | No 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-topabove 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
announceoff there. With a router that has no announcer of its own, turnannounceon, or a screen reader user hears nothing about the new page after Back or Forward. - Give every route a
document.titlethat 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(orselector) insidecontainerRef(the document when absent) whenkeychanges.keyis 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.scrollRestorationis'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 warningroute-focus-target-missing, nothing else). - A fragment link (a skip link, a table of contents) fires
popstatetoo but leaves the key alone, so it never marks the next navigation as a Back or Forward: the hook compares the address recorded atpopstatewith 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 onbody. 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. Withannounceon, 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 withscroll-padding-topfor a sticky header (2.4.11 Focus Not Obscured (Minimum), level AA). - The ring shows under
:focus-visibleonly (the maintainer's decision). The browser does not show it on a pointer-initiatedfocus(). 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
announcethrough 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.
| Key | Where | What happens |
|---|---|---|
| Tab | after a navigation | Continues after the focused h1, into the page's first stopTest: use-route-focus.test.tsx › keyboard › Tab after a navigation continues after the title |
| Shift+Tab | after a navigation | Goes back to the stop before the h1 (the header), not to the old linkTest: use-route-focus.test.tsx › keyboard › Shift+Tab after a navigation goes back to the stop before the title |
| Enter | on the focused h1 | Not 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).
| When | What it says | Message key | Politeness |
|---|---|---|---|
after the move, with announce | routeFocus.navigated | Polite | |
Back or Forward that moved no focus ('auto'), with announce | routeFocus.navigated | Polite |
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 action | Read aloud | Politeness | Test |
|---|---|---|---|
Back or Forward under 'auto', announce on | Navigated to {title}, focus stays | polite | use-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
| Prop | Type | Default | Description |
|---|---|---|---|
key | string | Required | The router’s location as a string: the pathname plus the search, never the hash. Focus moves when it changes. |
containerRef | RefObject<Element | null> | the document | Where to look for the selector: the element that holds the page. |
selector | string | 'h1' | The element to focus. If it has no tabindex of its own, it gets tabindex="-1" for as long as it has focus. |
announce | boolean | false | Also 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. |
messages | Partial<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.
| Language | Default text |
|---|---|
| Svenska | Du har kommit till {title} |
| Suomi | Siirryit sivulle {title} |
| Norsk bokmål | Du har kommet til {title} |
| Norsk nynorsk | Du har kome til {title} |
| English | Navigated to {title} |
Known issues#
- Back and Forward under
scrollRestoration: 'auto'move no focus. After Back or Forward underscrollRestoration: 'auto', focus is not moved and stays onbody, to keep the restored reading position. Withannounceoff 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 + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | route-focus.stories.tsx, every story, 4 themes (apps/storybook/src/components/focus/) |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | use-route-focus.test.tsx › first load does not move focus or touch the title; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 3 rows, each names a test (use-route-focus.test.tsx › keyboard › Tab after a navigation continues after the title) |
| Focus order and management | pass | n/a | pass | use-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/a | n/a | n/a | draws nothing itself; the focus ring on the focused h1 is the theme's general focus rule |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending | |
| Component-specific | ||||
| Next.js announcer doubled or not | pending | pending | pending |