T8 React Router

Unknown routes

The fallback parameter of the route-matching function at(route, x, y) can be used as a way to handle unknown routes, as shown in the example below. In a type-safe setup, unknown routes can be handled based on whether the given route belongs to the URL schema (e.g. with validate(route) from url-shape).

import { A, useRoute } from "@t8/react-router";

const routeMap = {
  intro: "/intro",
  sections: /^\/sections\/(?<id>\d+)\/?$/,
};

const knownRoutes = Object.values(routeMap);

let App = () => {
  let { at } = useRoute();

  return (
    <>
      <nav>
        <A href={routeMap.intro}>Intro</A>
      </nav>
      {at(routeMap.intro, <Intro/>)}
      {at(routeMap.sections, ({ params }) => (
        <Section id={params.id}/>
      ))}
      {at(knownRoutes, null, <Error/>)}
    </>
  );
};

The last at() in this example results in null (that is no content) for all known routes and renders the error content for the rest unknown routes.

🔹 at() calls don't have to maintain a specific order, and the at() call handling unknown routes doesn't have to be the last.

🔹 at() calls don't have to be grouped side by side like in the example above, their collocation is not a requirement. at() calls are not coupled together, they can be split across separate components and files (like any other conditionally rendered components).