@k8ordo/router

Navigation APIと<a>で画面を切り替える、型の付いたReactのルーター

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>

<a>のままのリンク

<Router>は<a>のクリックをNavigation APIで受け取り、ルート表にあるパスならページを読み込み直さずに画面を切り替えます。<Link>のような専用のコンポーネントはありません。

表に無いパスや再読み込み、POSTの送信、ダウンロードはブラウザに任せます。今どのページにいるかはuseMatchで調べます。

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>
  );
}

ルート表で検査されるパス

hrefとnavigateToは、ルート表のパターンを文字列で受け取ります。足りないparamは設定なしでも型エラーになり、Registerにルート表を登録すると表に無いパターンも型エラーになります。

ページはルート表をimportせず、リンク先をパターンの文字列だけで書きます。ルート表とページが互いにimportし合う循環は起きません。

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' });
表に無いパターンなので型エラーになる
href('/products/:id');
:idが無いので型エラーになる

ページの切り替えの待機とアニメーション

navigateToが返すfinishedは、新しいページが画面に表示されたときに解決します。useTransitionの中で待てば、isPendingは切り替えの間だけtrueになります。

ページの切り替えには、Reactのトランジションの種類としてnavigationが付きます。<ViewTransition>のupdateでnavigationだけを'auto'にすると、ページを切り替えるときだけアニメーションします。

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>