T8 React Router

Unknown routes

The fallback parameter of the route-matching function withRoute(routePattern, x, y) can be used as a way to handle unknown routes:

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

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

const knownRoutes = Object.values(routeMap);

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

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

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

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

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