T8 React Router
Routing
The following example shows the most essential parts of routing code. The route-matching function withRoute(routePattern, x, y)
acts similarly to the conditional operator matchesRoutePattern ? x : y
and is equally applicable to components and prop values. The route link component is similar to the HTML link tag.
import { A, useRoute } from "@t8/react-router";
import { Intro } from "./Intro";
import { Section } from "./Section";
let App = () => {
let { withRoute } = useRoute();
return (
<>
<header className={withRoute("/", "full", "compact")}>
<h1>App</h1>
<nav>
<A href="/">Intro</A>{" | "}
<A href="/sections/1">Section 1</A>
</nav>
</header>
{withRoute("/", <Intro/>)}
{withRoute(/^\/sections\/(?<id>\d+)\/?$/, ({ params }) => (
<Section id={params.id}/>
))}
</>
);
};
🔹 As mentioned above, withRoute(routePattern, x, y)
acts similarly to the conditional operator matchesRoutePattern ? x : y
: it returns x
if the current URL matches routePattern
, 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.
🔹 withRoute()
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
{withRoute("/about", <About/>)}
// With Activity
<Activity mode={withRoute("/about", "visible", "hidden")}>
<About/>
</Activity>
← Intro | Navigation →