@brabander/routing-react-router
v0.5.4
Published
This library was generated with [Nx](https://nx.dev).
Readme
routing-react-router
This library was generated with Nx.
React Router adapter for @brabander/routing-core: typed navigation
(useRouting) and typed route param retrieval (useRouteParams) for web
apps built on React Router.
Gebruik
1. Routes definiëren
Definieer je routes als een Record<string, string> met as const, zodat
TypeScript de exacte routenamen en :param/:param? segmenten kan afleiden:
const routes = {
home: '/',
profile: '/profile/:id',
'profile-edit': '/profile/:id/edit/:tab?',
} as const;2. Routes registreren op paginacomponenten
Koppel elke route aan een paginacomponent door rawPath als path-prop
aan React Router's <Route> te geven. rawPath geeft het pad-patroon
terug zoals het in routes staat (dus mét :id/:tab?) — precies het
formaat dat de path-prop verwacht. Zo blijft routes de enige bron van
waarheid voor elk pad, in plaats van dat het patroon nogmaals hardcoded
moet worden bij de route-registratie:
import { Route, Routes } from 'react-router';
import { useRouting } from '@brabander/routing-react-router';
function App() {
const { rawPath } = useRouting(routes);
return (
<Routes>
<Route path={rawPath('home')} element={<HomePage />} />
<Route path={rawPath('profile')} element={<ProfilePage />} />
<Route path={rawPath('profile-edit')} element={<ProfileEditPage />} />
</Routes>
);
}3. Navigeren met useRouting
import { useRouting } from '@brabander/routing-react-router';
const { goTo, path, rawPath, replace, back } = useRouting(routes);
goTo('home'); // geen params nodig
goTo('profile', { id: '42' }); // verplichte param
goTo('profile-edit', { id: '42' }); // optionele tab mag weg
goTo('profile-edit', { id: '42', tab: 'security' }); // beide params
goTo('profile'); // ❌ TypeScript error: id ontbreekt
path('profile', { id: '42' }); // '/profile/42' — bouwt het pad zonder te navigeren
rawPath('profile-edit'); // '/profile/:id/edit/:tab?' — ongeïnterpoleerd patroon
replace('profile', { id: '7' }); // navigeert met history.replace i.p.v. push
back(); // navigate(-1)4. Route params uitlezen met useRouteParams
import { useRouteParams } from '@brabander/routing-react-router';
// binnen een <Route path="/profile/:id/edit/:tab?"> element
const { id, tab } = useRouteParams(routes, 'profile-edit');
// id: string, tab: string | undefined — getypeerd op basis van de routeroutes en de routenaam worden hier alleen gebruikt om het returntype af te
leiden; het uitlezen zelf gebeurt via React Router's eigen useParams.
Beide hooks zijn dunne, getypeerde wrappers rond React Router's
useNavigate/useParams. De type-logica (RouteParams, buildPath,
route-validatie) zit in de framework-agnostische @brabander/routing-core
port — zie die package voor de onderliggende implementatie.
Running unit tests
Run nx test routing-react-router to execute the unit tests via Vitest.
