@molecule/app-routing-react-router

Provider bond · routing · App (browser) · v1.10.2 · Apache-2.0

React Router provider with URL-backed list pagination, filters, path/query selections and auth readiness

npm install @molecule/app-routing-react-router

npm · Source on GitHub · Implements @molecule/app-routing

How it works

@molecule/app-routing-react-router is a provider bond on the app (browser) side: it implements the routing core interface (@molecule/app-routing) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

import { ListRouteNav } from '@molecule/app-routing-react-router'
import { useTranslation } from '@molecule/app-react'

function OrderViews() {
  const { t } = useTranslation()
  return (
    <ListRouteNav
      aria-label={t('orders.views', undefined, { defaultValue: 'Order views' })}
      selections={{
        all: {
          path: '/orders',
          query: { view: undefined },
          label: t('orders.all', undefined, { defaultValue: 'All orders' }),
        },
        open: {
          path: '/orders',
          query: { view: 'open' },
          label: t('orders.open', undefined, { defaultValue: 'Open orders' }),
        },
      }}
    >
      {({ selection, page }) => <OrderResults view={selection} page={page} />}
    </ListRouteNav>
  )
}

Works with: @molecule/app-bond, @molecule/app-i18n, @molecule/app-react, @molecule/app-routing

Live demos

Running apps built with Molecule that install this package — open the app or study the template.

Reference

React Router (v7/v8) provider for @molecule/app-routing.

This package provides a React Router implementation of the molecule Router interface, allowing you to use molecule's routing abstractions with React Router.

useMoleculeRouter, useMoleculeQuery, useMoleculeNavigate, and useIsActive work inside any React Router router (BrowserRouter, HashRouter, MemoryRouter, Router, or RouterProvider), from this package or React Router itself. No MoleculeRouterProvider is required for these hooks. This package's router components render MoleculeRouterProvider themselves; under React Router's own, mount it to give @molecule/app-react's routing hooks (useLocation, useParams, RoutedView) the router, to bond the adapter for non-React @molecule/app-routing navigate()/getRouter(), to supply named routes, or to receive onRouterReady. Hook-created adapters remain local so multiple consumers cannot overwrite the global router bond.

With HTTP and auth clients bonded, BrowserRouter, HashRouter, and MemoryRouter replace the current URL with /login after a credential-free GET receives a 401 and the session is confirmed signed out. location.state.from holds the original location. Set signInPath to use a different sign-in route or pass signInPath={false} to opt out.

A route with parameters? Declare its page with defineRoute. The route path is the source of truth for the page's parameter names. Use { Component: Page } to receive a typed params prop automatically, or use the callback to supply a view selected by a literal suffix. For example:

import { defineRoute } from '@molecule/app-routing-react-router'

const routes = [
  defineRoute('/shelves/:shelf/edit', { Component: EditShelf }),
  defineRoute('/shelves/:shelf', ({ shelf }) => <Shelf name={shelf} view="all" />),
  defineRoute('/shelves/:shelf/saved', ({ shelf }) => <Shelf name={shelf} view="saved" />),
]

Keep the returned route when links or a save handler need its destination. For const detail = defineRoute('/shelves/:shelf', { Component: ShelfDetail }), use detail.href({ shelf: saved.slug }) to navigate to the saved record. A profile form can call it from useProfileForm's onSaved after it updates other caches.

Paginated or filtered page? Use useListRoute for its URL state. It reads page, filters and selected views from the current URL; builds links that retain the current path/filters; and resets page when a filter or view changes. Start with const pages = useListRoute(); filters and selections are optional. On /category/books matched by /category/:slug, pages.href({ page: 2 }) is /category/books?page=2 and pages.params.slug is 'books'. The route's path params need no extra config and never become duplicate query filters. On /?view=mine, the same call is /?view=mine&page=2: existing query keys keep their order, with page last. Page one omits page; unrelated queries and hash survive. Add path when changing path params, or selections when linking views. It works under ordinary BrowserRouter without a data router or an extra provider.

URL-selected tabs or filters? Render ListRouteNav. Declare each view's label, path and query together. It renders every declared choice on every route, builds each destination through useListRoute, resets pagination on selection, and derives the active link from the URL. Keep this declaration shared by the related routes. Give it a render function as children to use the same selection, params and page for the list query and links. Render loading and empty results inside that branch. Place the nav at the same level on each route, including a filtered route, so the controls remain available while the result changes. Pass list={{ className, itemClassName }} when the design uses a list of links. Use the UI package's Tabs for panels whose selection is genuinely local state.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { ListRouteNav } from '@molecule/app-routing-react-router'
import { useTranslation } from '@molecule/app-react'

function OrderViews() {
  const { t } = useTranslation()
  return (
    <ListRouteNav
      aria-label={t('orders.views', undefined, { defaultValue: 'Order views' })}
      selections={{
        all: {
          path: '/orders',
          query: { view: undefined },
          label: t('orders.all', undefined, { defaultValue: 'All orders' }),
        },
        open: {
          path: '/orders',
          query: { view: 'open' },
          label: t('orders.open', undefined, { defaultValue: 'Open orders' }),
        },
      }}
    >
      {({ selection, page }) => <OrderResults view={selection} page={page} />}
    </ListRouteNav>
  )
}
import { Routes, Route } from 'react-router'
import { BrowserRouter, MoleculeRouterProvider } from '@molecule/app-routing-react-router'

// Named, so generatePath('user', { id }) builds the path.
const namedRoutes = [{ name: 'user', path: '/users/:id' }]

function App() {
  // This package's BrowserRouter already renders a MoleculeRouterProvider, which bonds
  // the adapter (setRouter, before the pages run their effects), so
  // @molecule/app-routing's navigate()/getRouter() drive THIS real React Router — no
  // manual setRouter wiring needed. A provider inside it, as here, is optional: it uses
  // the outer one's router, registers its named routes and calls onRouterReady once.
  return (
    <BrowserRouter>
      <MoleculeRouterProvider routes={namedRoutes}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/users/:id" element={<UserProfile />} />
        </Routes>
      </MoleculeRouterProvider>
    </BrowserRouter>
  )
}

A list with query-selected views. The public URL remains public after login; a protected view waits for session restoration. Include the signed-in principal in the data key so one user's cached response cannot appear for another user, and pass null while the session is still restoring (status === 'loading') — the auth gate holds the request until then anyway, so waiting for it costs nothing.

import { Link } from 'react-router'
import { useAuth, useHttpClient, useTranslation } from '@molecule/app-react'
import { unwrapList } from '@molecule/app-http'
import { useQuery } from '@molecule/app-query-react'
import { useListRoute } from '@molecule/app-routing-react-router'

interface Entry {
  id: string
  title: string
}

function ActivityList() {
  const { status, user } = useAuth<{ id: string }>()
  const http = useHttpClient()
  const { t } = useTranslation()
  const list = useListRoute({
    pageSize: 10,
    filters: { category: { query: 'category' }, sort: { defaultValue: 'recent' } },
    selections: {
      public: { path: '/activity', query: { view: undefined } },
      personal: { path: '/activity', query: { view: 'personal' }, requiresAuth: true },
    },
    auth: { status, redirectTo: '/sign-in' },
  })
  const entries = useQuery(
    list.canLoad && status !== 'loading'
      ? {
          key: ['activity', user?.id ?? 'anonymous', list.selection, list.filters, list.page],
          fetch: async (signal) =>
            unwrapList<Entry>(
              await http.get('/api/activity', {
                signal,
                params: {
                  ...list.filters,
                  view: list.selection,
                  limit: list.pageSize,
                  offset: list.offset,
                },
              }),
            ),
        }
      : null,
  )
  return (
    <>
      <Link to={list.href({ selection: 'public' })}>
        {t('activity.public', undefined, { defaultValue: 'Public activity' })}
      </Link>
      {user && (
        <Link to={list.href({ selection: 'personal' })}>
          {t('activity.personal', undefined, { defaultValue: 'Your activity' })}
        </Link>
      )}
      <select
        value={list.filters.sort}
        onChange={(event) => list.setFilters({ sort: event.target.value })}
      >
        <option value="recent">
          {t('activity.recent', undefined, { defaultValue: 'Recent' })}
        </option>
        <option value="oldest">
          {t('activity.oldest', undefined, { defaultValue: 'Oldest' })}
        </option>
      </select>
      {entries.data?.map((entry) => (
        <p key={entry.id}>{entry.title}</p>
      ))}
      <Link to={list.href({ page: list.page + 1 })}>
        {t('activity.next', undefined, { defaultValue: 'Next page' })}
      </Link>
    </>
  )
}

Path-selected views and path-backed filters use the same hook. The browser route contract determines the URL; API filters can be derived separately from params.

// Mount the same page on /members/:member and /members/:member/saved.
const list = useListRoute({
  selections: {
    authored: { path: '/members/:member' },
    saved: { path: '/members/:member/saved' },
  },
})
// <Link to={list.href({ selection: 'saved' })}>…</Link> retains :member.
// list.href({ page: 2 }) stays on /members/:member/saved?page=2.
// Use list.params.member in the API request; it is not another query key.

// On /topics/:topic, changing page keeps the encoded topic in the path.
const topics = useListRoute({
  path: '/topics/:topic',
  filters: { topic: { param: 'topic' }, sort: { defaultValue: 'recent' } },
})
// topics.setFilters({ topic: 'type systems' }) changes the path and resets page.
// PaginationBar can use page={topics.page}, pageSize={topics.pageSize},
// onPageChange={topics.setPage}; custom links use topics.href({ page: next }).

One feed page on /, /?view=following and /topics/:topic: mount it on both routes with ONE config, so every tab link comes from href. With a separate config per route, the topic page cannot build the "all" link, and a hand-written one tends to keep the topic.

const feed = useListRoute({
  pageSize: 10,
  selections: {
    all: { path: '/', query: { view: undefined } },
    following: { path: '/', query: { view: 'following' } },
    topic: { path: '/topics/:topic' },
  },
  defaultSelection: 'all',
})
// On /topics/design?page=2: feed.selection is 'topic', feed.params.topic is 'design',
// feed.href({ selection: 'all' }) is '/', feed.href({ page: 3 }) is '/topics/design?page=3'.
// A topic link names its topic: feed.href({ selection: 'topic', params: { topic: name } }).

Type

provider

Installation

npm install @molecule/app-routing-react-router @molecule/app-bond @molecule/app-i18n @molecule/app-react @molecule/app-routing react react-router
npm install -D @types/react

API

Interfaces

ListRouteNavItem

A named list view and its navigation label.

interface ListRouteNavItem extends ListRouteSelection {
  /** Translated label, optionally including an icon. */
  label: ReactNode
  /** Path parameters for this destination; current route parameters are otherwise retained. */
  params?: RouteParams
  /** Keep the choice visible but prevent navigation. Authorization still belongs in the route. */
  disabled?: boolean
}

ListRouteNavItemState

URL-derived state available to the app's link styling.

interface ListRouteNavItemState<Selection extends string = string> {
  /** The app-owned selection key. */
  selection: Selection
  /** Whether the current URL selects this view. */
  active: boolean
  /** Whether navigation is disabled for this choice. */
  disabled: boolean
}

ListRouteNavProps

Props for URL-backed list navigation; local content panels use the UI package's Tabs instead.

interface ListRouteNavProps<Selection extends string = string> extends Omit<
  ComponentPropsWithoutRef<'nav'>,
  'children'
> {
  /** Accessible navigation name, translated by the app. */
  'aria-label': string
  /** Every declared view stays visible on every route; labels and targets share one declaration. */
  selections: Record<Selection, ListRouteNavItem>
  /** Tie-breaker or fallback, with the same meaning as useListRoute's defaultSelection. */
  defaultSelection?: NoInfer<Selection>
  /** Pagination query key to remove on selection, defaulting to page. */
  pageParam?: string
  /** Required for protected selections, with the same readiness rules as useListRoute. */
  auth?: ListRouteAuth
  /** Render links in a list, with optional classes for the list and its items. */
  list?: { className?: string; itemClassName?: string }
  /** App-owned styling, resolved from its class map. */
  linkClassName?: string | ((state: ListRouteNavItemState<Selection>) => string | undefined)
  /** Render the list beside the nav using its exact URL state, including resolved item params. */
  children?: (route: ListRouteResult<string, Selection>) => ReactNode
}

MoleculeRouterProviderProps

Provider props.

interface MoleculeRouterProviderProps {
  /**
   * Child components.
   */
  children: ReactNode

  /**
   * Optional route definitions for named routes.
   */
  routes?: RouteDefinition[]

  /**
   * Callback when router is ready.
   */
  onRouterReady?: (router: Router) => void
}

LazyPageOptions

Options for lazyPage.

interface LazyPageOptions {
  /** What the page's area shows while its code loads. Defaults to nothing. */
  fallback?: ReactNode
}

ReactRouterConfig

React Router-specific configuration.

interface ReactRouterConfig {
  /**
   * React Router navigate function (from useNavigate).
   */
  navigate?: NavigateFunction

  /**
   * Current location (from useLocation).
   */
  location?: {
    pathname: string
    search: string
    hash: string
    state?: unknown
    key?: string
  }

  /**
   * Current params (from useParams).
   */
  params?: Record<string, string | undefined>

  /**
   * Initial route definitions.
   */
  routes?: RouteDefinition[]
}

ReactRouterHooks

React Router hooks adapter.

interface ReactRouterHooks {
  /**
   * The navigate function from useNavigate.
   */
  navigate: NavigateFunction

  /**
   * Location from useLocation.
   */
  location: {
    pathname: string
    search: string
    hash: string
    state?: unknown
    key?: string
  }

  /**
   * Params from useParams.
   */
  params: Record<string, string | undefined>

  /**
   * Search params from useSearchParams.
   */
  searchParams: URLSearchParams
}

ListRouteFilter

Where a list filter lives in the URL. Path values take precedence over query values.

interface ListRouteFilter {
  /** Query key; defaults to the filter's name when `param` is absent. */
  query?: string
  /** Path parameter supplied by the current route, such as `category` in `/topics/:category`. */
  param?: string
  /** Value returned when neither URL source supplies a value; omitted from generated queries. */
  defaultValue?: string
}

ListRouteSelection

A selectable list view, expressed in the app's own route contract.

interface ListRouteSelection {
  /** Absolute route pattern, for example `/members/:member/saved`. */
  path: string
  /** Query values identifying this view. An undefined value requires the key to be absent. */
  query?: QueryParams
  /** A protected selection never loads before authentication is confirmed. */
  requiresAuth?: boolean
}

ListRouteAuth

Authentication readiness for protected list selections.

interface ListRouteAuth {
  /** The auth client's status. Unavailable is distinct from a signed-out session. */
  status: 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable'
  /** App-owned sign-in URL. A signed-out protected visit replaces history with this URL. */
  redirectTo: string
}

ListRouteOptions

URL-backed list state configuration; it neither invents nor rewrites the app's route contract.

interface ListRouteOptions<Filter extends string = string, Selection extends string = string> {
  /** Fixed number of items per page; defaults to 20. */
  pageSize?: number
  /** Query key for a 1-indexed page; defaults to `page`. Page one omits the key. */
  pageParam?: string
  /** Route pattern for changing path-backed filters when no selections are configured. */
  path?: string
  /** Filters and their URL sources. API-only filters do not belong here. */
  filters?: Record<Filter, ListRouteFilter>
  /** Named views sharing a list. Both path variants and query variants are supported. */
  selections?: Record<Selection, ListRouteSelection>
  /** Tie-breaker when multiple selections match, or fallback when none matches. */
  defaultSelection?: NoInfer<Selection>
  /** Required when a selection is protected. Public views remain public as auth changes. */
  auth?: ListRouteAuth
}

ListRouteChange

A single atomic list navigation. Filter/selection changes reset page unless explicitly supplied.

interface ListRouteChange<Filter extends string = string, Selection extends string = string> {
  /** Target page, starting at one. */
  page?: number
  /** Patch of URL filter values. Undefined removes a query filter. */
  filters?: Partial<Record<Filter, string | undefined>>
  /** Target view, resolved through its configured path and query values. */
  selection?: Selection
  /** Optional path parameter changes, for example when opening a different member's saved view. */
  params?: RouteParams
}

ListRouteResult

List state and navigation, derived directly from the current location.

interface ListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** Current 1-indexed page; malformed and non-positive URL values read as page one. */
  page: number
  /** Configured items per page. */
  pageSize: number
  /** Zero-indexed item offset for an API request. */
  offset: number
  /** Current URL filter values, including values supplied by path parameters. */
  filters: Record<Filter, string | undefined>
  /** Matching view, or the configured fallback. */
  selection: Selection | undefined
  /** Decoded current path parameters, also usable as API-only filters. */
  params: RouteParams
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  canLoad: boolean
  /** Readiness for the current view. A public view always stays ready. */
  status: 'ready' | 'loading' | 'unauthenticated' | 'unavailable'
  /** Sign-in destination while a signed-out protected view is being redirected. */
  redirectTo: string | undefined
  /** Build a real link target, preserving the current pathname, unrelated query values and hash. */
  href: (change?: ListRouteChange<Filter, Selection>) => string
  /** Navigate atomically. Location state is preserved unless options explicitly replace it. */
  navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
  /** Change only the page, retaining the current filters and view. */
  setPage: (page: number, options?: NavigateOptions) => void
  /** Patch URL filters and return to page one. */
  setFilters: (
    filters: Partial<Record<Filter, string | undefined>>,
    options?: NavigateOptions,
  ) => void
  /** Select a configured view at page one, preserving current route parameters. */
  select: (selection: Selection, options?: NavigateOptions) => void
}

RouteLocation

Current URL decomposed into pathname, search string, hash, navigation state, and unique key.

interface RouteLocation {
  /**
   * Current pathname.
   */
  pathname: string

  /**
   * Query string (including leading ?).
   */
  search: string

  /**
   * Hash (including leading #).
   */
  hash: string

  /**
   * State data passed with navigation.
   */
  state?: unknown

  /**
   * Unique key for this location.
   */
  key?: string
}

RouteMatch

Result of matching a URL against a route pattern (path, params, query string).

interface RouteMatch<Params extends RouteParams = RouteParams> {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Matched URL pathname.
   */
  pathname: string

  /**
   * Route parameters.
   */
  params: Params

  /**
   * Whether this is an exact match.
   */
  isExact: boolean
}

Options for programmatic navigation (replace vs push, carry state, preserve query/hash).

interface NavigateOptions {
  /**
   * Replace current history entry instead of pushing.
   */
  replace?: boolean

  /**
   * State to pass with navigation.
   */
  state?: unknown

  /**
   * Preserve current query params.
   */
  preserveQuery?: boolean

  /**
   * Preserve current hash.
   */
  preserveHash?: boolean
}

RouteDefinition

Route configuration entry (path pattern, name, auth requirements, roles, children).

interface RouteDefinition {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Route name (for named routes).
   */
  name?: string

  /**
   * Whether the route requires exact matching.
   */
  exact?: boolean

  /**
   * Whether the route requires authentication.
   */
  requiresAuth?: boolean

  /**
   * Required roles/permissions.
   */
  roles?: string[]

  /**
   * Route metadata.
   */
  meta?: Record<string, unknown>

  /**
   * Child routes.
   */
  children?: RouteDefinition[]
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

Types

LazyLoadableComponent

Any component React.lazy can load.

type LazyLoadableComponent = Awaited<ReturnType<Parameters<typeof lazy>[0]>>['default']

BrowserRouterProps

Props for BrowserRouter, with transitions permanently disabled.

type BrowserRouterProps = Omit<ReactRouterBrowserRouterProps, 'useTransitions'> & SignInPathProps

HashRouterProps

Props for HashRouter, with transitions permanently disabled.

type HashRouterProps = Omit<ReactRouterHashRouterProps, 'useTransitions'> & SignInPathProps

MemoryRouterProps

Props for MemoryRouter, with transitions permanently disabled.

type MemoryRouterProps = Omit<ReactRouterMemoryRouterProps, 'useTransitions'> & SignInPathProps

HistoryRouterProps

Props for unstable_HistoryRouter, with transitions permanently disabled.

type HistoryRouterProps = Omit<ReactRouterHistoryRouterProps, 'useTransitions'>

RouterProps

Props for Router, with transitions permanently disabled.

type RouterProps = Omit<ReactRouterProps, 'useTransitions'>

RouterProviderProps

Props for RouterProvider, with transitions permanently disabled.

type RouterProviderProps = Omit<ReactRouterProviderProps, 'useTransitions'>

StaticRouterProps

Props for StaticRouter: React Router's StaticRouterProps.

type StaticRouterProps = ReactRouterStaticRouterProps

StaticRouterProviderProps

Props for StaticRouterProvider: React Router's StaticRouterProviderProps.

type StaticRouterProviderProps = ReactRouterStaticRouterProviderProps

RouteParams

URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).

type RouteParams = Record<string, string>

QueryParams

URL query string parameter map (single values or arrays for repeated keys).

type QueryParams = Record<string, string | string[] | undefined>

GuardResult

Navigation guard result.

type GuardResult = boolean | string | { path: string; replace?: boolean } | void

Navigation guard function invoked before each navigation. Return false to cancel, a string/path to redirect, or void to allow.

type NavigationGuard = (
  to: RouteLocation,
  from: RouteLocation | null,
) => GuardResult | Promise<GuardResult>
  • to — The target route location being navigated to.
  • from — The current route location being navigated away from, or null on initial load.

RouteChangeListener

Callback invoked on each route change with the new location and the navigation action that triggered it.

type RouteChangeListener = (location: RouteLocation, action: NavigationAction) => void

Functions

ListRouteNav(props)

Render every declared list view as a router link. The URL selects the active choice, and selecting any view resets pagination through useListRoute. Native link behavior (new-tab clicks, keyboard activation and history) is preserved. This is a navigation landmark, not an ARIA tablist with local panels. No active-value state or change handler is needed. When children are supplied, they render after the navigation landmark. Put loading and empty results in that branch so a pending list never removes the filter controls.

function ListRouteNav<Selection extends string>({
  selections,
  defaultSelection,
  pageParam,
  auth,
  list,
  linkClassName,
  children,
  ...rest
}: ListRouteNavProps<Selection>): JSX.Element
  • props — Named destinations, translated labels, optional auth and native nav attributes.

Returns: The navigation landmark with all its choices, followed by any rendered content.

defineRoute(path, page)

Register a literal React Router path and give its page the params that path declares.

Create the route at module scope, then add it to the table passed to useRoutes or spread it into a Route. Pass { Component: EditPage } to give the page a typed params prop automatically. A render callback can also supply app-owned props, such as a view selected by a literal suffix. Keep page hooks inside the page component. In nested routes, layout components own the params declared on their own paths.

Use the returned href for links and post-save navigation. It builds the destination from the same path that mounts the page, with the parameter names required by that path. Pass values from the saved response when identity can change.

function defineRoute<const Path extends string>(
  path: Path,
  page:
    | ((params: NoInfer<Params<PathParam<Path>>>) => ReactNode)
    | { Component: ComponentType<{ params: NoInfer<Params<PathParam<Path>>> }> },
): Pick<RouteObject, 'element'> & { path: Path; href: (...args: LinkArgs<Path>) => string }
  • path — A route path, including any named parameters.
  • page — A component receiving params, or a function building the page element.

Returns: The route table entry and a function that builds a link to it.

MoleculeRouterProvider(props)

Provider component that creates ONE molecule Router over React Router for its whole mounted life and bonds it as the active singleton via @molecule/app-routing's setRouter. Subscribers and guards registered on the router survive navigation: @molecule/app-routing's getRouter() keeps returning it, onRouterReady fires once, and React Router's own links and the back button reach router.subscribe(). It also renders @molecule/app-react's RouterProvider with the router and React Router's Outlet as the routed view, so that binding's routing hooks and RoutedView work.

This bond's BrowserRouter, HashRouter, MemoryRouter, Router and unstable_HistoryRouter already render one around their children, and its data-router RouterProviders build the molecule router from the data router they are given. Mount it yourself for named routes or onRouterReady, or under React Router's own router components; in framework mode (HydratedRouter), mount it in the root route. Inside another one it creates no second router: it registers its routes on the outer router and calls onRouterReady with it.

Bonding happens in a layout effect on mount, before the pages' effects run, so @molecule/app-routing's navigate()/getRouter() drive THIS real React Router adapter.

function MoleculeRouterProvider(props: MoleculeRouterProviderProps): React.JSX.Element
  • props — The provider props (see MoleculeRouterProviderProps): children (rendered inside the router context), routes (optional named-route definitions; pass a stable array — later identities register onto the same router), and onRouterReady (optional callback invoked ONCE with the router after it is bonded, e.g. to register guards — bonding via setRouter happens regardless).

Returns: The rendered provider wrapping children with the router context.

useMoleculeRouter()

Hook to get the molecule Router inside any React Router router, including BrowserRouter, HashRouter, MemoryRouter, Router, or RouterProvider from this package or React Router itself. No MoleculeRouterProvider is required.

Under a provider (every router component of this package renders one), returns that router as the calling component sees it: getParams() answers with the params of the route the component renders in (React Router's useParams), and everything else — location, navigation, subscribers, guards, named routes — is the provider's router. The object stays the same for the component's life, but it is not === getRouter(). Under React Router's own router components with no provider, creates ONE router for the calling component's whole life — its location, params and queries follow React Router through every navigation, and subscribe() hears React Router's own links and the back button — without bonding it globally.

function useMoleculeRouter(): Router

Returns: The molecule Router instance

useIsActive(path, exact)

Hook to check if a path is currently active inside any React Router router. MoleculeRouterProvider is optional; mount it only for named routes, the non-React navigate()/getRouter() bond, or onRouterReady.

function useIsActive(path: string, exact?: boolean): boolean
  • path — Path to check
  • exact — Whether to require exact match

Returns: Whether the path is active

useMoleculeNavigate()

Hook to get a navigate function with molecule Router options inside any React Router router. MoleculeRouterProvider is optional; mount it only for named routes, the non-React navigate()/getRouter() bond, or onRouterReady.

function useMoleculeNavigate(): Router['navigate']

Returns: Navigate function

useMoleculeQuery()

Hook to get current query params as an object inside any React Router router. MoleculeRouterProvider is optional; mount it only for named routes, the non-React navigate()/getRouter() bond, or onRouterReady.

function useMoleculeQuery(): QueryParams

Returns: Query params object

useConsumedSearchParam(name)

Consume a credential query parameter into component state and remove only that parameter from the address through React Router. The value survives local rerenders, StrictMode, failed-submit retries and later query-only navigation; a newly arriving value on the same mounted route is consumed too and shows one commit later. Path, hash, unrelated query values and router location state are retained.

React Router owns the URL replacement, so useLocation() and window.location agree. A metadata-only history merge retains unrelated pre-existing top-level state fields that React Router does not model; it never changes the URL or the router's usr/key/idx fields.

function useConsumedSearchParam(name: string): readonly [string, Dispatch<SetStateAction<string>>]
  • name — The credential query key to consume, for example token or code.

Returns: The consumed value and its state setter; the value is empty before first consumption.

lazyPage(load, options)

Load a route's page on demand, inside a Suspense boundary that belongs to the page.

Use it instead of React.lazy for every page a <Route> renders. Navigating to a page whose code has not loaded yet then replaces the previous page at once: the previous page unmounts and the new page's own boundary shows fallback until its code arrives. With React.lazy under one shared <Suspense> around <Routes>, React keeps the previous page mounted (hidden) behind that boundary's fallback, so the URL already names the new page while the old page's content is still in the DOM, and a check such as getByRole('heading') finds the old page's headings. Layout routes (an app shell around <Outlet />) stay mounted either way.

function lazyPage<Page extends LazyLoadableComponent>(
  load: () => Promise<{ default: Page }>,
  options?: LazyPageOptions,
): ComponentType<NonNullable<ComponentProps<Page>>>
  • load — Loads the page module, as for React.lazy: () => import('./pages/Article.js').then((m) => ({ default: m.Article })).
  • options — Optional fallback shown in the page's area while its code loads.

Returns: A component to use as a route's element: <Route path="/article/:slug" element={<Article />} />. Its props are the page's own, without the undefined an optional props parameter (function Draft({ initial }: DraftProps = {})) adds: a component type carrying it is not a valid JSX element type wherever React's types resolve from a second copy.

createReactRouter(config)

Creates a React Router adapter that implements the molecule Router interface over a config snapshot: the navigate function, location and params of one render. The snapshot never changes, so every read answers for that render — the hooks (MoleculeRouterProvider, useMoleculeRouter) build the live router instead, one that follows React Router for its whole life. Navigation runs React Router's navigate, falling back to a full-page window.location navigation when no navigate was given (the hook-less provider).

function createReactRouter(config?: ReactRouterConfig): Router
  • config — Configuration with React Router's navigate function, location, params, and optional routes.

Returns: A molecule Router with navigation, guards, query/hash management, and route matching.

BrowserRouter(props)

Browser router that commits the URL and rendered page together.

function BrowserRouter({
  children,
  signInPath = DEFAULT_SIGN_IN_PATH,
  ...props
}: BrowserRouterProps): JSX.Element

HashRouter(props)

Hash router that commits the URL and rendered page together.

function HashRouter({
  children,
  signInPath = DEFAULT_SIGN_IN_PATH,
  ...props
}: HashRouterProps): JSX.Element

MemoryRouter(props)

In-memory router that commits its location and rendered page together.

function MemoryRouter({
  children,
  signInPath = DEFAULT_SIGN_IN_PATH,
  ...props
}: MemoryRouterProps): JSX.Element

Router(props)

Low-level router that commits its location and rendered page together.

function Router({ children, ...props }: RouterProps): JSX.Element

RouterProvider(props)

Data-router provider that commits the URL and rendered page together.

This is React Router's renderer-neutral provider. In a DOM app, import RouterProvider from @molecule/app-routing-react-router/dom instead, which supplies react-dom's flushSync the way react-router/dom does.

function RouterProvider(props: RouterProviderProps): JSX.Element

unstable_HistoryRouter(props)

History router that commits the URL and rendered page together.

function unstable_HistoryRouter({ children, ...props }: HistoryRouterProps): JSX.Element

StaticRouter(props)

Server-render router for one location (a prerender or an SSR request), with the molecule router over it, so @molecule/app-react's routing hooks, Link and RoutedView render there as they do in the browser. React Router's own StaticRouter gives them no router.

function StaticRouter({ children, ...props }: StaticRouterProps): JSX.Element
  • props — React Router's StaticRouterProps: location (the path to render), basename and children.

Returns: React Router's StaticRouter with the molecule router around children.

StaticRouterProvider(props)

Server-render provider for a static data router (createStaticRouter over a createStaticHandler query), with the molecule router built from it, as RouterProvider does in the browser.

function StaticRouterProvider(props: StaticRouterProviderProps): JSX.Element
  • props — React Router's StaticRouterProviderProps: router, context and hydrate.

Returns: React Router's StaticRouterProvider under the molecule router.

useListRoute(options)

Own URL-backed pagination, filters and selected views without mirrored state or navigation effects. Works inside BrowserRouter, MemoryRouter and data routers; no data-router-only useNavigation call or MoleculeRouterProvider is needed. Ordinary links, direct visits, and Back/Forward all read the same URL. Page links retain path parameters and unrelated queries; changing filters or views resets the page atomically. Protected views wait for auth and redirect only a confirmed signed-out session, with state.returnTo set.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: ListRouteOptions<Filter, Selection>,
): ListRouteResult<Filter, Selection>
  • options — App-owned filter sources, view paths, pagination and optional auth readiness.

Returns: Reactive list state plus link builders and navigation actions. Gate data queries with canLoad.

parseSearchParams(searchParams)

Converts URLSearchParams into QueryParams. A key that appears more than once becomes an array of its values, in order.

function parseSearchParams(searchParams: URLSearchParams): QueryParams
  • searchParams — The search params to read.

Returns: The query params.

stringifyQuery(params)

Serializes QueryParams into a query string with a leading ?, percent-encoding keys and values (a space is %20). Undefined values are left out; an array writes its key once per value.

function stringifyQuery(params: QueryParams): string
  • params — The query params.

Returns: The query string, or '' when there is nothing to write.

matchPath(pattern, pathname, exact)

Matches a route pattern against a pathname. :name captures one segment and * matches anything. The whole pathname must match unless exact is false, which also accepts a pathname that only starts with the pattern.

function matchPath<Params extends RouteParams = RouteParams>(
  pattern: string,
  pathname: string,
  exact?: boolean,
): RouteMatch<Params> | null
  • pattern — The pattern, such as /users/:id or /files/*.
  • pathname — The pathname to match.
  • exact — Whether the whole pathname must match (default true).

Returns: The match with its params, or null.

generatePath(pattern, params)

Builds a path from a pattern by putting each :name param in its place, percent-encoded. A pattern given no params is returned as it is.

function generatePath(pattern: string, params?: RouteParams): string
  • pattern — The pattern, such as /users/:id.
  • params — The param values.

Returns: The path.

resolvePath(to, fromPathname)

Resolves a path against the pathname it is relative to: an absolute to is returned as it is; otherwise to is joined to fromPathname's parent, with .. moving up and . staying.

function resolvePath(to: string, fromPathname: string): string
  • to — The path to resolve.
  • fromPathname — The pathname it is relative to.

Returns: The resolved pathname.

normalizePath(path)

Removes trailing slashes from a path, keeping / itself.

function normalizePath(path: string): string
  • path — The path.

Returns: The path without trailing slashes.

Constants

provider

Default React Router provider (basic, no hooks). For full functionality, use createReactRouter with useNavigate/useLocation/useParams.

const provider: Router

Core Interface

Implements @molecule/app-routing interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setRouter } from '@molecule/app-routing'
import { provider } from '@molecule/app-routing-react-router'

export function setupRoutingReactRouter(): void {
  setRouter(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-auth ^1.4.0 || ^2.0.0 || ^3.0.0 (optional)
  • @molecule/app-bond ^1.0.1
  • @molecule/app-http ^1.10.0 (optional)
  • @molecule/app-i18n ^1.0.1
  • @molecule/app-react ^4.11.0 || ^5.0.0
  • @molecule/app-routing ^1.5.0
  • react ^18.0.0 || ^19.0.0
  • react-dom ^18.0.0 || ^19.0.0 (optional)
  • react-router ^7.0.0 || ^8.0.0

Runtime Dependencies

  • @molecule/app-auth (optional)

  • @molecule/app-bond

  • @molecule/app-http (optional)

  • @molecule/app-i18n

  • @molecule/app-react

  • @molecule/app-routing

  • react

  • react-dom (optional)

  • react-router

  • useListRoute derives state from the URL on every render, including Back/Forward. Do not mirror selection/page in local state or rewrite an explicit public view when auth changes. Auth redirects replace the protected history entry only after a confirmed unauthenticated status; loading and unavailable remain in place.

  • Pass null to useQuery when list.canLoad is false or while the session is still restoring (status === 'loading'). Public views stay ready; protected views do not fall back to a public request while auth is unresolved.

  • A selection's query owns only its configured keys. undefined means absent; unrelated query values and the hash survive pagination and selection changes. Filter/selection changes reset page one atomically, unless page is explicit.

  • useListRoute does not call React Router's useNavigation: that hook needs a data router and throws under BrowserRouter. Use the data query's isFetching for list loading. No UI library, CSS class map, or data cache is required by the hook.

  • MoleculeRouterProvider bonds the router for you. On mount it calls @molecule/app-routing's setRouter with the live adapter, so other molecule packages' navigate()/getRouter() drive React Router (real SPA navigation) — no manual wiring. Pass onRouterReady only if you also need the router instance (e.g. to register guards); bonding happens either way.

  • Do NOT wire the exported provider const in a React Router app — it is a no-hooks fallback (empty params, window.location.href navigation). Use MoleculeRouterProvider (or createReactRouter with hook values) instead.

  • The provider must live INSIDE a React Router router (it calls React Router hooks).

  • A page reads its route params from the hooks. @molecule/app-react's useParams and useMoleculeRouter().getParams() read React Router's match for the calling component, with no route definitions. Code outside components that calls getRouter().getParams() under BrowserRouter, HashRouter or MemoryRouter reads the registered route definitions only, because only a component can see React Router's match. Pass the params in from the page, or use a data router (RouterProvider from /dom): its router knows the matched route, so getParams() reads it anywhere.

  • Import router components from this bond, never directly from React Router. Each one gives the app its molecule router, which @molecule/app-react's routing hooks, Link, RoutedView and every molecule layout and guard read; under React Router's own they have no router and throw. The client ones also turn transitions off, so a navigation renders the new route in the same commit as the URL change. A server render uses this bond's StaticRouter (or StaticRouterProvider for a static data router). Import non-router APIs (Routes, Route, Link, hooks) from 'react-router'. A DOM data router's RouterProvider and the framework-mode HydratedRouter come from @molecule/app-routing-react-router/dom.

  • Declare pages loaded on demand with lazyPage, not React.lazy. Each page then has a Suspense boundary of its own, so navigating to a page whose code is still loading removes the previous page at once. Under one shared <Suspense> around <Routes>, React keeps the previous page mounted (hidden) until the new code arrives, while the URL already names the new page.