Skip to main content
jg-packages

Search

    React Router

    jg-react-router

    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.

    v0.5.0BrowserESMMIT

    npm

    npm install jg-react-router

    pnpm

    pnpm add jg-react-router

    Usage

    A page outlet

    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.

    tsx
    import { createBrowserRouter } from 'react-router';
    import { PageOutlet } from 'jg-react-router';
    import 'jg-react-router/styles.css';
    
    export const router = createBrowserRouter([
      {
        path: '/',
        element: <PageOutlet className="app-main" />,
        children: [
          { index: true, element: <HomePage /> },
          { path: 'settings', element: <SettingsPage /> },
        ],
      },
    ]);

    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:

    tsx
    import { RouterProvider } from 'react-router';
    import { DialogNavigationProvider } from 'jg-react-router';
    
    export const App = () => (
      <DialogNavigationProvider>
        <RouterProvider router={router} />
        <ConfirmDialogHost />
      </DialogNavigationProvider>
    );

    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:

    tsx
    import { createBrowserRouter } from 'react-router';
    import {
      createLazyPageComponent,
      createPageRouteObject,
      type IPageRouteDefinition,
      PageOutlet,
    } from 'jg-react-router';
    
    const PAGES: IPageRouteDefinition<{ navigationLabel: string }>[] = [
      {
        path: '/',
        title: 'Home',
        description: 'Your dashboard.',
        navigationLabel: 'Home',
        Component: HomePage,
      },
      {
        path: '/settings',
        title: 'Settings',
        description: 'Your account and notifications.',
        navigationLabel: 'Settings',
        lazy: createLazyPageComponent(() => import('./settings.page.js')), // loads when visited
      },
    ];
    
    export const router = createBrowserRouter([
      { element: <PageOutlet />, children: PAGES.map((page) => createPageRouteObject(page)) },
    ]);

    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=2
    setFilters({ ...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 payment
    const linkState = pageReturn.createState(`${location.pathname}${location.search}`, location.state);
    
    // on the payment, with its own back link to /payments
    const { 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.

    Functions

    createLazyPageComponent

    function

    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.

    Signature
    createLazyPageComponent(
      loadModule: () => Promise<{ default: ComponentType<IPageRouteMetadata> }>,
    ): IPageRouteLazyFunction

    Parameters

    loadModule() => Promise<{ default: ComponentType<IPageRouteMetadata> }>

    Imports the page's module.

    Returns

    IPageRouteLazyFunction

    The lazy function.

    Example
    import { createLazyPageComponent } from 'jg-react-router';
    
    declare const importSettings: Parameters<typeof createLazyPageComponent>[0];
    
    const lazy = createLazyPageComponent(importSettings); // such as () => import('./settings.page.js')

    createLazyRoute

    function

    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.

    Signature
    createLazyRoute<TModule extends object, TProps extends object = object>(
      load: IRouteModuleLoader<TModule>,
      select: (module: TModule) => ComponentType<TProps>,
    ): ILazyRoute<TProps>

    Parameters

    loadIRouteModuleLoader<TModule>

    What imports the module.

    select(module: TModule) => ComponentType<TProps>

    Picks the route's component from the module.

    Returns

    ILazyRoute<TProps>

    The route's lazy function.

    Throws

    • ROUTE_MODULE_UNAVAILABLEThe page's code couldn't be loaded.
    Example
    import { createBrowserRouter } from 'react-router';
    import { createLazyRoute } from 'jg-react-router';
    
    declare const importSettings: () => Promise<{ SettingsPage: () => null }>;
    
    export const router = createBrowserRouter([
      { path: '/settings', lazy: createLazyRoute(importSettings, (module) => module.SettingsPage) },
    ]);

    createPageReturn

    function

    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.

    Signature
    createPageReturn(options: IPageReturnOptions): IPageReturn

    Parameters

    optionsIPageReturnOptions

    The state key, the excluded paths, and the app's origins.

    Returns

    IPageReturn

    The functions.

    Example
    import { createPageReturn, retainSearchParams } from 'jg-react-router';
    
    const LABELS: Record<string, string> = { '/payments': 'Payments', '/projects': 'All projects' };
    
    export const pageReturn = createPageReturn({
      excludedPaths: ['/sign-in'],
      resolveOrigin: (url) => {
        const label = Object.hasOwn(LABELS, url.pathname) ? LABELS[url.pathname] : undefined;
        const search = retainSearchParams(url.searchParams, { status: { defaultValue: 'all' } });
        return label === undefined || search === null
          ? null
          : { href: `${url.pathname}${search.size > 0 ? `?${search.toString()}` : ''}`, label };
      },
    });
    
    pageReturn.createState('/payments?status=failed'); // => { pageReturn: { href: '/payments?status=failed' } }

    createPageRouteElement

    function

    Renders a page component with its title and description as its props.

    Signature
    createPageRouteElement(
      PageComponent: ComponentType<IPageRouteMetadata>,
      pageMetadata: IPageRouteMetadata,
    ): ReactElement

    Parameters

    PageComponentComponentType<IPageRouteMetadata>

    The component.

    pageMetadataIPageRouteMetadata

    The title and description.

    Returns

    ReactElement

    The element.

    Example
    import { createPageRouteElement, type IPageRouteComponentProps } from 'jg-react-router';
    
    declare const SettingsPage: (props: IPageRouteComponentProps) => null;
    
    const element = createPageRouteElement(SettingsPage, { title: 'Settings', description: 'Your account.' });

    createPageRouteHandle

    function

    Creates the handle a page route carries, which usePageRouteMetadata reads.

    Signature
    createPageRouteHandle(pageMetadata: IPageRouteMetadata): IPageRouteHandle

    Parameters

    pageMetadataIPageRouteMetadata

    The page's title and description.

    Returns

    IPageRouteHandle

    The handle.

    Example
    import { createPageRouteHandle } from 'jg-react-router';
    
    const handle = createPageRouteHandle({ title: 'Settings', description: 'Your account.' });

    createPageRouteMetadata

    function

    Picks a page's title and description from its route definition, leaving out every other field.

    Signature
    createPageRouteMetadata(pageRoute: IPageRouteMetadata): IPageRouteMetadata

    Parameters

    pageRouteIPageRouteMetadata

    The definition, or anything with a title and a description.

    Returns

    IPageRouteMetadata

    The metadata.

    Example
    import { createPageRouteMetadata } from 'jg-react-router';
    
    const settings = { path: '/settings', title: 'Settings', description: 'Your account.' };
    createPageRouteMetadata(settings); // { title: 'Settings', description: 'Your account.' }

    createPageRouteObject

    function

    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.

    Signature
    createPageRouteObject<TExtraFields extends object>(
      pageRoute: IPageRouteDefinition<TExtraFields>,
      options?: ICreatePageRouteObjectOptions,
    ): RouteObject

    Parameters

    pageRouteIPageRouteDefinition<TExtraFields>

    The definition.

    options?ICreatePageRouteObjectOptions

    The fallback for lazy routes, and the wrapper for every element.

    Defaults to {}.

    Returns

    RouteObject

    The route object.

    Example
    import { createBrowserRouter } from 'react-router';
    import { createLazyPageComponent, createPageRouteObject } from 'jg-react-router';
    
    declare const importSettings: Parameters<typeof createLazyPageComponent>[0];
    
    export const router = createBrowserRouter([
      createPageRouteObject({
        path: '/settings',
        title: 'Settings',
        description: 'Your account and notifications.',
        lazy: createLazyPageComponent(importSettings),
      }),
    ]);

    DialogNavigationObserver

    function

    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.

    Signature
    DialogNavigationObserver(
      props: IDialogNavigationObserverProps,
    ): ReactElement<unknown, string | JSXElementConstructor<any>> | null

    Parameters

    propsIDialogNavigationObserverProps

    Whether it belongs to the root error screen.

    Returns

    ReactElement<unknown, string | JSXElementConstructor<any>> | null

    The observer, or null outside a provider.

    Example
    import { createElement } from 'react';
    import { createBrowserRouter, Outlet } from 'react-router';
    import { DialogNavigationObserver } from 'jg-react-router';
    
    export const router = createBrowserRouter([
      {
        path: '/',
        element: createElement('div', null, createElement(DialogNavigationObserver), createElement(Outlet)),
        errorElement: createElement(DialogNavigationObserver, { isErrorScreen: true }),
      },
    ]);

    DialogNavigationProvider

    function

    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.

    Signature
    DialogNavigationProvider(props: IDialogNavigationProviderProps): ReactElement

    Parameters

    propsIDialogNavigationProviderProps

    The router and the dialog hosts.

    Returns

    ReactElement

    The provider.

    Example
    import { createElement } from 'react';
    import { RouterProvider, type createBrowserRouter } from 'react-router';
    import { DialogNavigationProvider } from 'jg-react-router';
    
    declare const router: ReturnType<typeof createBrowserRouter>;
    declare const DialogHost: () => null;
    
    // the router's root route renders <DialogNavigationObserver />
    export const App = () =>
      createElement(
        DialogNavigationProvider,
        null,
        createElement(RouterProvider, { router }),
        createElement(DialogHost),
      );

    loadRouteModule

    function

    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.

    Signature
    loadRouteModule<TModule extends object>(
      load: IRouteModuleLoader<TModule>,
    ): Promise<TModule>

    Parameters

    loadIRouteModuleLoader<TModule>

    What imports the module.

    Returns

    Promise<TModule>

    A promise that resolves to the module.

    Throws

    • ROUTE_MODULE_UNAVAILABLEThe page's code couldn't be loaded.
    Example
    import { loadRouteModule } from 'jg-react-router';
    
    declare const importSettings: () => Promise<{ SettingsPage: () => null }>;
    
    export const loadSettings = () => loadRouteModule(importSettings);

    PageOutlet

    function

    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.

    Returns

    ReactElement

    The frame with the child route.

    Example
    import { createElement } from 'react';
    import { createBrowserRouter } from 'react-router';
    import { PageOutlet } from 'jg-react-router';
    
    declare const HomePage: () => null;
    declare const SettingsPage: () => null;
    
    export const router = createBrowserRouter([
      {
        path: '/',
        element: createElement(PageOutlet, { className: 'app-main' }),
        children: [
          { index: true, element: createElement(HomePage) },
          { path: 'settings', element: createElement(SettingsPage) },
        ],
      },
    ]);

    retainSearchParams

    function

    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.

    Signature
    retainSearchParams(
      source: URLSearchParams,
      rules: Readonly<Record<string, IRetainedSearchParamRule>>,
    ): URLSearchParams | null

    Parameters

    sourceURLSearchParams

    The page's parameters.

    rulesReadonly<Record<string, IRetainedSearchParamRule>>

    Each kept parameter's schema and default.

    Returns

    URLSearchParams | null

    The kept parameters, or null when one is repeated or isn't valid, so the page isn't offered as a way back.

    Example
    import { retainSearchParams } from 'jg-react-router';
    import { z } from 'zod';
    
    const kept = retainSearchParams(new URLSearchParams('status=open&lookup=ada%40example.com'), {
      status: { schema: z.enum(['all', 'open']), defaultValue: 'all' },
    });
    kept?.toString(); // 'status=open', without the private lookup

    useDialogNavigationDismissal

    function

    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.

    Signature
    useDialogNavigationDismissal(options: IDialogNavigationDismissalOptions): void

    Parameters

    optionsIDialogNavigationDismissalOptions

    How to read the dialog's session, and how to close it.

    Example
    import { useState } from 'react';
    import { useDialogNavigationDismissal } from 'jg-react-router';
    
    export const useConfirmDialog = () => {
      const [session, setSession] = useState<object | null>(null);
      useDialogNavigationDismissal({
        getSession: () => session,
        onDismiss: () => {
          setSession(null);
        },
      });
      return { isOpen: session !== null, open: () => setSession({}), close: () => setSession(null) };
    };

    usePageReturn

    function

    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.

    Signature
    usePageReturn(
      pageReturn: IPageReturn,
      options?: IResolvePageReturnOptions,
    ): IPageReturnResolution

    Parameters

    pageReturnIPageReturn

    The app's page return, from createPageReturn.

    options?IResolvePageReturnOptions

    The page the current one's own back link leads to.

    Defaults to {}.

    Returns

    IPageReturnResolution

    The way back, and the state to return with.

    Example
    import { createPageReturn, usePageReturn } from 'jg-react-router';
    
    declare const pageReturn: ReturnType<typeof createPageReturn>;
    
    export const useBackLink = () => {
      const { returnTo, returnState } = usePageReturn(pageReturn, { parentHref: '/payments' });
      return returnTo === null
        ? { href: '/payments', label: 'Payments', state: undefined }
        : { ...returnTo, state: returnState };
    };

    usePageRouteMetadata

    function

    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.

    Example
    import { useEffect } from 'react';
    import { usePageRouteMetadata } from 'jg-react-router';
    
    export const useDocumentTitle = () => {
      const pageMetadata = usePageRouteMetadata();
      useEffect(() => {
        document.title = pageMetadata === null ? 'App' : `${pageMetadata.title} | App`;
      }, [pageMetadata]);
    };

    useSearchParamDialog

    function

    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.

    Signature
    useSearchParamDialog(name: string): ISearchParamDialog

    Parameters

    namestring

    The search parameter, such as event.

    Returns

    ISearchParamDialog

    The open ID, empty while none is open, and what opens and closes the dialog.

    Example
    import { useSearchParamDialog } from 'jg-react-router';
    
    export const useEventDialog = () => useSearchParamDialog('event');

    useSearchParamState

    function

    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'.

    Signature
    useSearchParamState<T extends object>(
      options: IUseSearchParamStateOptions<T>,
    ): [T, ISetSearchParamState<T>]

    Parameters

    optionsIUseSearchParamStateOptions<T>

    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.
    Example
    import { useSearchParamState } from 'jg-react-router';
    import { z } from 'zod';
    
    const FiltersSchema = z.object({
      query: z.string(),
      page: z.coerce.number().int().min(1),
      tags: z.array(z.string()),
    });
    
    export const usePaymentFilters = () =>
      useSearchParamState({
        params: { query: 'one', page: 'one', tags: 'many' },
        schema: FiltersSchema,
        defaultValue: { query: '', page: 1, tags: [] },
      });

    Constants

    DEFAULT_PAGE_RETURN_STATE_KEY

    const

    the router state key an origin is kept under by default

    Declaration
    const DEFAULT_PAGE_RETURN_STATE_KEY: "pageReturn"

    ERRORS

    const

    the codes for every error thrown by the package

    Declaration
    const ERRORS: { INVALID_SEARCH_PARAM_VALUE: "INVALID_SEARCH_PARAM_VALUE"; ROUTE_MODULE_UNAVAILABLE: "ROUTE_MODULE_UNAVAILABLE" }

    Types

    ICreatePageRouteObjectOptions

    type

    what createPageRouteObject takes besides the definition

    Declaration
    type ICreatePageRouteObjectOptions = {
        HydrateFallback?: RouteObject['HydrateFallback'] | undefined;
        wrapElement?: ((element: ReactElement, pageMetadata: IPageRouteMetadata) => ReactElement) | undefined;
    };

    Members

    • HydrateFallbackproperty
      RouteObject["HydrateFallback"]

      shown while a lazy page loads during hydration

    • wrapElementproperty
      (element: ReactElement, pageMetadata: IPageRouteMetadata) => ReactElement

      wraps every page's element, such as in a layout or an error boundary

    IDialogNavigationDismissalOptions

    type

    what useDialogNavigationDismissal takes: how to read the dialog's session, and how to close it, which must happen synchronously

    Declaration
    type IDialogNavigationDismissalOptions = {
        getSession: IDialogNavigationSessionReader;
        onDismiss: () => void;
    };

    Members

    • getSessionproperty
      IDialogNavigationSessionReader
    • onDismissproperty
      () => void

    IDialogNavigationObserverProps

    type

    what DialogNavigationObserver takes

    Declaration
    type IDialogNavigationObserverProps = {
        isErrorScreen?: boolean | undefined;
    };

    Members

    • isErrorScreenproperty
      boolean

      whether the observer belongs to the root error screen, which replaces the route without changing its location key

    IDialogNavigationProviderProps

    type

    what DialogNavigationProvider takes: the router and the dialog hosts that share its navigation

    Declaration
    type IDialogNavigationProviderProps = {
        children?: ReactNode;
    };

    Members

    • childrenproperty
      ReactNode

    IDialogNavigationSessionReader

    type

    reads a dialog's open session: a stable object for as long as that session lasts, or null while the dialog is closed

    Declaration
    type IDialogNavigationSessionReader = () => object | null;

    ILazyRoute

    type

    what a lazy route resolves to: the component its module exports

    Declaration
    type ILazyRoute<TProps extends object> = () => Promise<{
        Component: ComponentType<TProps>;
    }>;

    IPageOutletProps

    type

    what PageOutlet takes

    Declaration
    type IPageOutletProps = {
        className?: string | undefined;
        transitionKey?: string | undefined;
    };

    Members

    • classNameproperty
      string

      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

    IPageReturn

    type

    records where a navigation came from, and resolves the way back to it

    Declaration
    type IPageReturn = {
        createState: (href: string, state?: unknown) => Record<string, unknown>;
        resolve: (state: unknown, currentHref: string, options?: IResolvePageReturnOptions) => IPageReturnResolution;
        normalizeOrigin: (candidate: unknown) => IPageReturnOrigin | null;
    };

    Members

    • createStateproperty
      (href: string, state?: unknown) => Record<string, unknown>

      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

    • resolveproperty
      (state: unknown, currentHref: string, options?: IResolvePageReturnOptions) => IPageReturnResolution

      the way back from the current page, given the router state it was reached with

    • normalizeOriginproperty
      (candidate: unknown) => IPageReturnOrigin | null

      a candidate href as the page to return to, or null when it isn't one

    IPageReturnOptions

    type

    what createPageReturn takes

    Declaration
    type IPageReturnOptions = {
        stateKey?: string | undefined;
        excludedPaths?: readonly string[] | undefined;
        resolveOrigin: (url: URL) => IPageReturnOrigin | null;
    };

    Members

    • stateKeyproperty
      string

      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

    IPageReturnOrigin

    type

    a page to return to: its href, with only the query it keeps, and the label of the link back

    Declaration
    type IPageReturnOrigin = {
        href: string;
        label: string;
    };

    Members

    • hrefproperty
      string
    • labelproperty
      string

    IPageReturnResolution

    type

    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

    Declaration
    type IPageReturnResolution = {
        returnTo: IPageReturnOrigin | null;
        returnState: Record<string, unknown> | undefined;
    };

    Members

    • returnToproperty
      IPageReturnOrigin | null
    • returnStateproperty
      Record<string, unknown> | undefined

    IPageRouteComponentProps

    type

    the props a page component receives: exactly its route's title and description

    Declaration
    type IPageRouteComponentProps = IPageRouteMetadata;

    IPageRouteDefinition

    type

    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.

    Declaration
    type IPageRouteDefinition<TExtraFields extends object = object> = IPageRouteMetadata & TExtraFields & {
        path: string;
    } & ({
        Component: ComponentType<IPageRouteComponentProps>;
        lazy?: never;
    } | {
        Component?: never;
        lazy: IPageRouteLazyFunction;
    });

    IPageRouteHandle

    type

    the handle a page route carries, which usePageRouteMetadata reads from the matches

    Declaration
    type IPageRouteHandle = {
        pageMetadata: IPageRouteMetadata;
    };

    Members

    • pageMetadataproperty
      IPageRouteMetadata

    IPageRouteLazyFunction

    type

    loads a page component on demand, such as from a dynamic import

    Declaration
    type IPageRouteLazyFunction = () => Promise<{
        Component: ComponentType<IPageRouteComponentProps>;
    }>;

    IPageRouteMetadata

    type

    a page's title and description, kept with its route

    Declaration
    type IPageRouteMetadata = {
        title: string;
        description: string;
    };

    Members

    • titleproperty
      string
    • descriptionproperty
      string

    IResolvePageReturnOptions

    type

    how resolve treats the current page

    Declaration
    type IResolvePageReturnOptions = {
        parentHref?: string | undefined;
    };

    Members

    • parentHrefproperty
      string

      the page the current one's own back link leads to, so an origin equal to it isn't offered

    IRetainedSearchParamRule

    type

    how retainSearchParams keeps one parameter

    Declaration
    type IRetainedSearchParamRule = {
        schema?: ISchema<unknown> | undefined;
        defaultValue?: string | undefined;
    };

    Members

    • schemaproperty
      ISchema<unknown>

      checks the value, throwing for one that isn't valid, such as a Zod enum

    • defaultValueproperty
      string

      the value the page shows without the parameter, which is left out

    IRouteModuleLoader

    type

    imports a route's module on demand, such as () => import('./settings.page.js')

    Declaration
    type IRouteModuleLoader<TModule extends object> = () => Promise<TModule>;

    ISchema

    type

    a validator with a parse method that returns valid data or throws, such as a Zod schema

    Declaration
    type ISchema<T> = {
        parse(value: unknown): T;
    };

    Members

    • parsemethod
      parse(value: unknown): T

    ISearchParamDialog

    type

    what useSearchParamDialog returns

    Declaration
    type ISearchParamDialog = {
        openId: string;
        open: (id: string) => void;
        close: () => void;
    };

    Members

    • openIdproperty
      string

      the ID of what the open dialog shows, or an empty string while it's closed

    • openproperty
      (id: string) => void

      opens the dialog on an ID, adding a history entry

    • closeproperty
      () => void

      closes the dialog: back past the entry its opening added, or in place

    ISearchParamKind

    type

    how a search parameter holds its value: once, such as ?page=2, or repeated, such as ?tag=a&tag=b

    Declaration
    type ISearchParamKind = 'one' | 'many';

    ISearchParamKinds

    type

    each owned key's kind

    Declaration
    type ISearchParamKinds<T> = {
        readonly [K in keyof T]: ISearchParamKind;
    };

    ISetSearchParamState

    type

    changes the state, from a value or from an updater given the latest value

    Declaration
    type ISetSearchParamState<T> = (next: T | ((current: T) => T), options?: ISetSearchParamStateOptions) => void;

    ISetSearchParamStateOptions

    type

    how a state change navigates

    Declaration
    type ISetSearchParamStateOptions = {
        replace?: boolean | undefined;
    };

    Members

    • replaceproperty
      boolean

      replaces the history entry instead of adding one. Defaults to false

    IUseSearchParamStateOptions

    type

    what useSearchParamState takes

    Declaration
    type IUseSearchParamStateOptions<T extends object> = {
        params: ISearchParamKinds<T>;
        schema: ISchema<T>;
        defaultValue: T;
        unknownParams?: 'preserve' | 'remove' | undefined;
    };

    Members

    • paramsproperty
      ISearchParamKinds<T>

      the keys the state owns, each as 'one' or 'many'

    • schemaproperty
      ISchema<T>

      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