React Router helpers: a page outlet that restores focus and scroll, dialogs kept in the URL or closed on navigation, and pages whose code fails to load.
PageOutlet renders the matched child route in a frame. Each new page gets focus, without scrolling, so assistive technology starts reading at it, and the window scrolls to the top. Back and Forward restore where the page was scrolled instead, retrying while its content loads, until the user scrolls or types. A navigation that changes only the query, such as a filter, keeps the page and its scroll.
The stylesheet gives the frame its full width and a short fade, which reduced motion turns off. It sits in the base cascade layer, so the app’s own styles and Tailwind CSS utilities override it. A layout whose nested routes should share one frame, such as a settings page with tabs, passes its own transitionKey.
Closing dialogs when the route changes
A dialog left open across a navigation covers the new page. DialogNavigationProvider closes the dialogs that are open when a navigation commits, before the new page’s effects run:
The router’s root route renders <DialogNavigationObserver />, and its error element <DialogNavigationObserver isErrorScreen />, so a route error closes them too. Each dialog host calls useDialogNavigationDismissal with a reader for its open session, an object that stays the same while the dialog is open, and a function that closes it. Hosts that share a session close it once, and without a provider the hook does nothing.
Page routes with their metadata
Keep each page’s path, title, and description in one route map, and let createPageRouteObject build the router’s routes from it. Each page component receives exactly { title, description } as its props, and usePageRouteMetadata reads the deepest matched page’s, such as for the document’s title:
An eager page becomes { path, handle, element }, and a lazy one { path, handle, HydrateFallback, lazy }, whose lazy resolves to the element. The wrapElement option wraps every page’s element, such as in an error boundary, and HydrateFallback shows while a lazy page loads during hydration. usePageRouteMetadata skips a handle without a string title and description, and gives null when no matched route is a page.
Route code that couldn’t load
After a deploy, the scripts an open tab’s build names are gone, and offline they can’t be fetched, so a lazy route’s import fails. createLazyRoute builds a route’s lazy function from a module’s named export, and rejects that failure with ROUTE_MODULE_UNAVAILABLE, which the route’s error element can tell from the page’s own errors:
tsx
import { useRouteError } from 'react-router';import { hasErrorCode } from 'jg-exception';import { createLazyRoute, ERRORS } from 'jg-react-router';const RouteError = () => { const error = useRouteError(); if (!hasErrorCode(error, ERRORS.ROUTE_MODULE_UNAVAILABLE)) throw error; return <ReloadNotice />; // the page opens once the app reloads};const routes = [ { path: '/settings', errorElement: <RouteError />, lazy: createLazyRoute( () => import('./settings.page.js'), (module) => module.SettingsPage, ), },];
loadRouteModule(load) is the same check for any module a route loads. Both reject an import that resolves with no module too, as Vite’s does once a vite:preloadError handler prevented the error, and keep a failed import as the exception’s cause.
URL state
useSearchParamState keeps typed state, such as a list’s filters and page, in the URL’s search parameters, so a reload, a shared link, and Back all show the same list:
ts
import { useSearchParamState } from 'jg-react-router';import { z } from 'zod';const FiltersSchema = z.object({ query: z.string(), page: z.coerce.number().int().min(1), status: z.array(z.enum(['paid', 'refunded'])),});const [filters, setFilters] = useSearchParamState({ params: { query: 'one', page: 'one', status: 'many' }, // ?status=paid&status=refunded schema: FiltersSchema, // a rejected URL reads as the defaults defaultValue: { query: '', page: 1, status: [] }, // left out of the URL});setFilters((current) => ({ ...current, page: current.page + 1 })); // pushes ?page=2setFilters({ ...filters, query: 'card', page: 1 }, { replace: true }); // replaces the entry
The schema reads the URL’s strings, with the defaults filling missing keys, so give numbers and booleans z.coerce or a preprocess step. The URL holds the canonical form, without keys at their defaults, and a URL that isn’t canonical, such as an old bookmark, is replaced once, keeping the router state and the hash, so the way back to the previous page isn’t lost. Components that own keys in the same URL build on each other’s repair, so two that own the same keys replace it once. The value keeps its identity while its keys don’t change, and the setter always keeps its identity. Changes made in the same tick compose, each updater seeing the one before, and navigate once; a change that leaves the search as it is navigates nowhere. Parameters the state doesn’t own, such as utm_source, stay, unless unknownParams is 'remove'. A value the URL can’t hold, such as an object or NaN, throws INVALID_SEARCH_PARAM_VALUE where it’s set.
Each change is a navigation, so DialogNavigationProvider closes the dialogs open at the time, as for any other navigation.
Dialogs in the URL
useSearchParamDialog keeps a page’s open dialog in one search parameter, holding the ID of what it shows, so a link or a reload opens it, and Back, or the system back gesture on a phone, closes it:
tsx
import { useSearchParamDialog } from 'jg-react-router';const { openId, open, close } = useSearchParamDialog('event'); // ?event=event-7// <button onClick={() => open(event.id)}>, and <EventDialog id={openId} open={openId !== ''} onClose={close} />
Opening adds a history entry, marked in its router state, and close goes back past it, so the dialog never lingers in history, whichever component opens or closes it. A dialog the URL opened as the page loaded closes in place, replacing the entry and keeping the other parameters. An empty ID, or one longer than 4,096 characters, reads as closed. These are navigations, so a dialog that DialogNavigationProvider closes takes a session reader that returns null, and a link that moves it to another ID keeps the router state, so Back still closes it.
Page return
createPageReturn gives a detail page a way back to the page it was opened from, such as a filtered list, kept in the router state rather than the URL. The app says which pages it returns to, with their labels and the query each keeps:
ts
import { createPageReturn, retainSearchParams, usePageReturn } from 'jg-react-router';import { z } from 'zod';const LABELS: Record<string, string> = { '/payments': 'Payments', '/projects': 'All projects' };export const pageReturn = createPageReturn({ excludedPaths: ['/sign-in'], // never a way back resolveOrigin: (url) => { const label = Object.hasOwn(LABELS, url.pathname) ? LABELS[url.pathname] : undefined; const search = retainSearchParams(url.searchParams, { status: { schema: z.enum(['all', 'failed']), defaultValue: 'all' }, // left out at all }); return label === undefined || search === null ? null : { href: `${url.pathname}${search.size > 0 ? `?${search.toString()}` : ''}`, label }; },});// on the list, linking to a paymentconst linkState = pageReturn.createState(`${location.pathname}${location.search}`, location.state);// on the payment, with its own back link to /paymentsconst { returnTo, returnState } = usePageReturn(pageReturn, { parentHref: '/payments' });// returnTo: { href: '/payments?status=failed', label: 'Payments' }, or null
An origin must be a safe internal path, not under excludedPaths, that resolveOrigin accepts, and its hash is dropped. retainSearchParams keeps only the parameters its rules list, each at most once and valid, leaving out one at its default, so a search box’s private text never reaches the state; a repeated or invalid parameter offers no way back. createState replaces an earlier origin and keeps the rest of the state. usePageReturn offers no way back to the parent, the current page, or its pathname, and gives the state to return with without the origin, so the way back is used once. A state that isn’t valid offers none.
Generated from TSDoc
API reference
Every export of [email protected], 45 in all, with its signature, its errors, and an example.
Turns a dynamic import of a module whose default export is a page component into a page route's lazy function, so the page's code loads only when its route is visited.
Builds a route's lazy function from its module and the component it exports by name, loading the module through loadRouteModule, so a module that couldn't be loaded rejects with ROUTE_MODULE_UNAVAILABLE for the route's error element.
Creates the way back to the page a navigation came from, such as a list a detail page was opened from, kept in the router state rather than the URL. createState(href, state) records the page in the state of the navigation away from it, replacing an earlier origin and keeping the rest of the state. resolve(state, currentHref) gives the page to return to and its label, with the state to return with, which no longer holds the origin, so the way back is used once.
An origin must be a safe internal path, not under excludedPaths, which resolveOrigin accepts: it gives the label, and keeps only the query it allows, such as through retainSearchParams. The hash is dropped. No way back is offered to the current page, its pathname, or parentHref, the page the current one's own back link leads to, and a state that isn't valid offers none.
Turns a page route's definition into a React Router route object: the page's element, with its title and description as its props, under a handle that usePageRouteMetadata reads. An eager route renders its component; a lazy one loads it when visited, with HydrateFallback shown while it loads during hydration. wrapElement wraps the element either way.
Reports each committed navigation to the surrounding DialogNavigationProvider, in a layout effect, so open dialogs close before the new page's effects open its own. Render it once in the router's root route, and with isErrorScreen in its error element, so a route error closes the dialogs too. Outside a provider, it renders nothing and needs no router.
Closes the dialogs that are open when a navigation commits, without touching history: each dialog host registers with useDialogNavigationDismissal, and a DialogNavigationObserver inside the router reports each committed location. It reads every open session before closing any, so a dialog that closes or replaces another can't make the provider skip or close the wrong one, and hosts that share a session close it once. Without a provider, the hook and the observer do nothing.
Loads a route's module, telling a failed load apart from the page's own errors, so the route's error element can offer a reload instead of crashing: after a deploy, the scripts the open app's build names are gone, and offline they can't be fetched. A failed import rejects with ROUTE_MODULE_UNAVAILABLE, keeping the failure as its cause, and so does an import that resolves with no module, which Vite does once a vite:preloadError handler prevented the error.
Renders the matched child route in a frame that orients each new page: it focuses the frame, without scrolling, and scrolls the window to the top. Back and Forward restore the position the page had instead, retrying while its content loads and grows, until the user scrolls, touches, clicks, or types. A navigation that changes only the query keeps the page and its scroll. While an outlet is mounted, history.scrollRestoration is manual. Import jg-react-router/styles.css for the frame's layout and its fade, which reduced motion turns off.
Signature
PageOutlet(props: IPageOutletProps): ReactElement
Parameters
propsIPageOutletProps
The frame's extra classes, and the key that identifies the page.
Keeps the search parameters a page's rules allow, for the href to return to it: each at most once, valid for its schema, and left out at its default. Every other parameter, such as a search box's private text, is dropped.
Closes a dialog when a navigation commits while its session is open, through the surrounding DialogNavigationProvider. It always calls the latest getSession and onDismiss the component committed, so they needn't be stable, and it closes the session only if getSession still returns the one that was open when the navigation committed. Outside a provider, it does nothing.
Resolves the way back to the page the current one was reached from, from the current location's router state, as pageReturn.resolve does: the page to return to and its label, or null, and the state to navigate back with, which no longer holds the origin.
Gives the title and description of the deepest matched page route, such as for the document's title or a page header in a layout. A handle without a string title and description is skipped.
Signature
usePageRouteMetadata(): IPageRouteMetadata | null
Returns
IPageRouteMetadata | null
The page's metadata, or null when no matched route is a page route.
Keeps a page's open dialog in one search parameter, which holds the ID of what it shows, so a link or a reload opens it. Opening adds a history entry, marked in its router state, so Back, and the system back gesture on a phone, close it. Closing it otherwise goes back past that entry, so it never lingers, whichever of the page's components opens or closes it. A dialog the URL opened as the page loaded closes in place, replacing the entry. An empty ID, or one longer than 4,096 characters, reads as closed.
The dialog's own navigations must not close it: a dialog that closes when the route changes, such as through useDialogNavigationDismissal, takes a session reader that returns null. A link that moves the dialog to another ID keeps the router state, so Back still closes it.
Keeps typed state, such as a list's filters and page, in the URL's search parameters. It reads the owned keys through the schema, with the defaults filling missing keys, and falls back to defaultValue when the schema rejects them. The URL holds the state's canonical form, without keys at their defaults; a URL that isn't canonical, such as an old bookmark, is replaced once, keeping the router state and the hash, so the way back to the previous page isn't lost. Components that own keys in the same URL build on each other's repair, so one that owns the same keys as another replaces nothing more. The value keeps its identity while the URL's owned keys don't change.
The setter keeps its identity, takes a value or an updater, and pushes a history entry unless given replace. Changes made in the same tick compose, each updater seeing the one before it, and navigate once, keeping the router state and the hash; a change to the current search navigates nowhere. Parameters the state doesn't own stay, unless unknownParams is 'remove'.
The owned keys, the schema, the defaults, and what happens to other keys.
Returns
[T, ISetSearchParamState<T>]
The value, and its setter.
Throws
INVALID_SEARCH_PARAM_VALUEA search parameter's value must be a string, a finite number, a boolean, null, or undefined, or a list of them for a repeated parameter.
classes added to the frame after jg-page-outlet, such as the app's layout classes
transitionKeyproperty
string
what identifies the page: a new value remounts the frame, focuses it, and scrolls to the top. Defaults to the location's pathname, so a navigation that changes only the query keeps the page. A parent route's own key keeps its frame while its nested routes change
the router state for a navigation from href: the current state, with the origin replacing an earlier one, or without one when href isn't a page to return to
the router state key the origin is kept under. Defaults to pageReturn
excludedPathsproperty
readonly string[]
paths an origin must not lead to, such as /sign-in, or anything under them
resolveOriginproperty
(url: URL) => IPageReturnOrigin | null
turns an origin's URL, already a safe internal path with no trailing slash and no hash, into the page to return to, with the label of the link back and only the query it keeps, such as through retainSearchParams, or null for a page the app doesn't return to
what resolve gives: the page to return to, or null, and the router state to return with, the current state without the origin, so the return doesn't offer a way back again
A page route's definition: its path, title, and description, any fields an app adds, such as a navigation label, and either its component or a function that loads it.
turns the URL's strings, with the defaults filling missing keys, into the state, such as a Zod schema with z.coerce; a value it rejects reads as defaultValue
defaultValueproperty
T
the state without parameters; a key at its default is left out of the URL
unknownParamsproperty
"preserve" | "remove"
what happens to the parameters the state doesn't own: 'preserve', the default, keeps them, and 'remove' drops them