@k8ordo/router

A typed React router that switches pages through the Navigation API and plain <a> links

bash
npm install @k8ordo/router
routes.ts
export const routes = defineRoutes({
  '/': Home,
  '/products': ProductList,
  '/products/:id': ProductPage,
});
app.tsx
export const App = () => <Router routes={routes} />;
product-card.tsx
<a href={href('/products/:id', { id: product.id })}>
  {product.name}
</a>

Links as plain <a>

<Router> receives clicks on <a> through the Navigation API. For a path in the route table, it changes the page without a full reload. There is no <Link> component.

A path outside the table, a reload, a POST submission and a download are left to the browser. useMatch tells you which page is showing.

products-link.tsx
export function ProductsLink({ children }: PropsWithChildren) {
  const current = useMatch('/products/*', { inclusive: true });

  return (
    <a
      aria-current={current ? 'page' : undefined}
      href={href('/products')}
    >
      {children}
    </a>
  );
}

Paths checked against the table

href and navigateTo take a pattern from the route table as a string. A missing param is a type error with no setup, and once the table is registered in Register, so is a pattern the table lacks.

A page never imports the table. It names its links by pattern string alone, so the table and its pages never import each other.

k8ordo-router.d.ts
declare module '@k8ordo/router' {
  interface Register {
    routes: typeof routes;
  }
}
product-card.tsx
href('/products/:id', { id: '42' });
// '/products/42'

href('/prodcuts/:id', { id: '42' });
Not a pattern in the table: a type error
href('/products/:id');
Missing :id: a type error

Awaiting and animating page changes

The finished promise from navigateTo resolves once the new page is on screen. Await it inside useTransition, and isPending is true only while the page changes.

Every page change carries the React transition type navigation. Set navigation to 'auto' in the update prop of <ViewTransition>, and only page changes animate.

open-product.tsx
const [isPending, startTransition] = useTransition();

startTransition(async () => {
  await navigateTo('/products/:id', { id }).finished;
});
layout.tsx
<ViewTransition
  default="none"
  update={{ navigation: 'auto', default: 'none' }}
>
  <Outlet />
</ViewTransition>