Skip to content

TomokiMiyauci/react-router

Repository files navigation

react-router

JSR GitHub

release standard-readme compliant

Next generation React router.

A minimal router based on URLPattern API and Navigation API. No more <Link> or <A>.

Table of Contents

Install

deno:

deno add @miyauci/react-router

npm:

npx jsr add @miyauci/react-router

Usage

The basic exclusive routing is as follows:

import {
  Route,
  Router,
  Switch,
  useURL,
  useURLPatternResult,
} from "@miyauci/react-router";
import { type ReactNode } from "react";

function Home(): ReactNode {
  const url = useURL();
  const result = useURLPatternResult();

  return <main>Home</main>;
}
declare const About: () => ReactNode;
declare const NotFound: () => ReactNode;

function App(props: { url?: string | URL }): ReactNode {
  return (
    <Router url={props.url}>
      <Switch fallback={<NotFound />}>
        <Route pathname="/">
          <Home />
        </Route>

        <Route pathname="/about">
          <About />
        </Route>
      </Switch>
    </Router>
  );
}

It is best practice to specify the url on the server side and nothing on the client side.

Client Side Navigation

Intercept the navigate event on client side navigation.

Add your client entry point:

globalThis.navigation.addEventListener("navigate", (e) => {
  // if (shouldNotIntercept(e)) return;
  e.intercept({
    async handler() {},
  });
});

This ensures that navigation is done only for URL changes. The Router will also subscribe to URL changes and route them reactively.

See Modern client-side routing: the Navigation API about shouldNotIntercept.

This script may be provided by this project in the future.

Polyfill

This project relies on a relatively new API.

The API and Polyfill are as follows:

API Polyfill
URLPattern urlpattern-polyfill
Navigation @virtualstate/navigation

Documentation

Remarks

This chapter supplements the project.

URLPatternList

This project is based on the URLPatternList interface. This API is still Draft, but will be replaced when it is generalized. This should further reduce the bundle size.

API

See jsr doc for all APIs.

Contributing

See contributing.

License

MIT © 2024 Tomoki Miyauchi