T8 React Router
Concise router for React apps
npm i @t8/react-router
🔹 Concise routing API
<header className={at("/", "full", "compact")}>
// at "/" ? "full" : "compact"
{at("/about", <About/>)}
// at "/about" ? <About/> : undefined
{at(/^\/sections\/(?<id>\d+)\/?$/, ({ params }) => (
<Section id={params.id}/>
))}
// at "/sections/<id>" ? <Section id={id}/> : undefined
🔹 Familiar navigation APIs
- <a href="/about">About</a>
+ <A href="/about">About</A> // SPA route link
- window.location.assign("/about");
+ route.assign("/about"); // SPA navigation
- window.location.href = "/about";
+ route.href = "/about"; // SPA navigation
🔹 Middleware hooks
useNavigationStart(callback);
// e.g. to redirect or prevent navigation
useNavigationComplete(callback);
// e.g. to set the document's title
🔹 Typed routes and URL parameters, as an optional enhancement
// ↓ type-safe URL pattern builder
let { url } = createURLSchema({
"/sections/:id": z.object({ // with Zod
params: z.object({ id: z.coerce.number() })
})
});
// ↓ { id: number }
{at(url("/sections/:id"), ({ params }) => (
<Section id={params.id}/>
))}
<A href={url("/sections/:id", { params: { id: 1 } })}>Section 1</A>
// ↑ { id: number }
🔹 URL parameters as state
let [state, setState] = useRouteState("/");
// with type safety based on a custom URL schema
let [state, setState] = useRouteState(url("/"));
🔹 Lazy routes
{at("/about", <Suspense><About/></Suspense>)}
🔹 SSR- and CSR-compatible