Route matching
Routescape offers a simple and consistent way to render both components and prop values in a single manner (unlike component-, config-, or file-based approaches) based on the current location:
import {useRoute} from 'routescape';
let App = () => {
let {route, withRoute} = useRoute();
// `withRoute(routePattern, x, y)` acts similarly to
// `matchesRoutePattern ? x : y`
return (
<>
<header className={withRoute('/', 'full', 'compact')}>
<h1>App</h1>
</header>
{withRoute('/', (
<main>
<h1>Intro</h1>
</main>
))}
{withRoute(/^\/sections\/(?<id>\d+)\/?$/, ({params}) => (
<main>
<h1>Section {params.id}</h1>
</main>
))}
</>
);
};
Note that both the header's className
prop and the <main>
component are rendered in a single way using the same route-matching function.
(With the component-based, config-based, or file-based route matching adopted by some routers, conditionally rendering a component and a prop value have to be handled differently.)
🔹 The ternary route-matching function withRoute(routePattern, x, y)
returned from the useRoute()
hook has the semantics similar to the ternary conditional operator matchesRoutePattern ? x : y
, commonly seen with the conditional rendering pattern, which reflects the fact that route-based rendering also falls under this category.
🔹 withRoute()
doesn't impose any route hierarchy by default, as it can be used with any route pattern anywhere in the app's components, offering sufficient flexibility to handle an arbitrary route-based logic.
🔹 withRoute()
accepts route patterns of various types: string | RegExp | (string | RegExp)[]
. The parameters of a regular expression route pattern (or of the first RegExp
match in the array) are passed to the second and the third parameter of withRoute()
if they are functions, as shown in the example above.
← Intro | Route navigation →