@t8/react-router

Route matching

Rendering based on the URL with @t8/react-router is similar to conditional rendering with the ternary operator matchesRoutePattern ? x : y, equally applicable to components and prop values and resulting in a single consistent approach for both. This is a contrast to the component-, config-, or file-based route matching which are typically focused on component rendering, while route-based prop values have to be handled differently.

import {useRoute} from '@t8/react-router';

let App = () => {
    let {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>
            ))}
        </>
    );
};

Live demo

Note that both the header's className prop and the <main> component are rendered in a single way using the same route-matching function.

🔹 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 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.