T8 React Router

Routing

The following example runs through the essential parts of routing code. The at(route, x, y) function returns a value based on whether the route parameter matches the current URL. It acts similarly to the conditional operator atRoute ? x : y and is equally applicable to components and prop values. The route link component that is used for SPA navigation acts and looks similar to the HTML link tag.

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

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

  return (
    <>
      <header className={at("/", "full", "compact")}>
        <h1>App</h1>
        <nav>
          <A href="/">Intro</A>{" | "}
          <A href="/sections/1">Section 1</A>
        </nav>
      </header>
      {at("/", <Intro/>)}
      {at(/^\/sections\/(?<id>\d+)\/?$/, ({ params }) => (
        <Section id={params.id}/>
      ))}
    </>
  );
};

Live demo

🔹 As mentioned above, at(route, x, y) acts similarly to the conditional operator atRoute ? x : y: it returns x if the current URL matches route, and y otherwise. Having the ternary function rather than the ternary conditional operator allows for additional flexibility, like omitting an undefined fallback parameter or resolving as a dynamic value based on params extracted from the route pattern, as seen in the example above.

🔹 at() calls are independent from each other, they don't have to maintain a certain order, they shouldn't be necessarily grouped in a single component (although they can be, as in the example above). Components with route-based logic can be split like any other components.

🔹 Route-based rendering with the React's <Activity> component looks similar to what we've seen in the example above:

// Without Activity
{at("/about", <About/>)}

// With Activity
<Activity mode={at("/about", "visible", "hidden")}>
  <About/>
</Activity>