Skip to content

amoshydra/react-router-dom-with-prefix

Repository files navigation

React Router DOM with Prefix

A drop-in replacement for react-router-dom that provides nested prefix routing.

 import {
+  PrefixedBrowserRouter,
   BrowserRouter,
   Routes,
   Route,
-} from "react-router-dom";
+} from "react-router-dom-with-prefix";

PrefixedBrowserRouter

PrefixedBrowserRouter is a provider that provides route prefix to the router components and functions wrapped within it.

<BrowserRouter basename="/prefix-1">
  <Routes>
    <Route path="/" element={<Outlet />}>
      <Route
        path="/prefix-a/*"
        element={
          <PrefixedBrowserRouter basename="/prefix-a">
            <Routes>
              {/* navigation inside PrefixedBrowserRouter are prefixed with "/prefix-a" */}
              <Route path="/nested-1" element={<Link to="/nested-2">Go 2</Link>} />
              <Route path="/nested-2" element={<Link to="/nested-1">Go 1</Link>} />
            </Routes>
          </PrefixedBrowserRouter>
        }
      />
      <Route path="/prefix-b" element={<PageB />} />
    </Route>
  </Routes>
</BrowserRouter>

Augmentation to react-router-dom exports

The following exports are augmented with prefix awared logic

  1. createPath
  2. useBlocker
  3. useHref
  4. useLinkClickHandler
  5. useLocation
  6. useMatch
  7. useNavigate
  8. useResolvedPath
  9. useRoutes

Components

  1. Link
  2. NavLink
  3. Navigate

Related to Data Router

  1. useMatches
  2. useSubmit

Motivation

Nesting of BrowserRouter is no longer support since v6.

Not patched

The following known exports are not augmented

Not needed

These function is not related to basename

  1. useNavigationType
  2. generatePath
  3. matchPath
  4. matchRoutes
  5. parsePath
  6. useRevalidator
  7. useParams
  8. resolvePath
  9. useBeforeUnload
  10. useInRouterContext
  11. useOutlet
  12. useOutletContext
  13. useSearchParams
Data router hooks
  1. useActionData
  2. useNavigation
  3. useLoaderData
  4. useRouteLoaderData
  5. useRouteError

Related to data fetching

  1. useFetcher
  2. useFetchers
  3. useFormAction

Related to Await

  1. Await
  2. useAsyncError
  3. useAsyncValue

Unknown

  1. redirect
  2. redirectDocument
  3. renderMatches