Group related routes using createGroup()
mainWhen rendering components based on active routes, checking for multiple related routes (like a parent and all its sub-routes) can become verbose. Use createGroup() to simplify this logic.
createGroup() allows you to bundle a set of routes into a single group. You can then use the .has(route) method on the group to check if the current active route belongs to that specific group. This is particularly useful for determining which layout or sub-page component should be rendered.
To use it:
- Pass an array of routes to
createGroup([...]). - Use
group.has(route)in your conditional rendering logic. - Use
Route<typeof group>to type the props of your sub-page components, ensuring they accept any route within that group.
import React from "react";
import {
Route,
defineRoute,
createRouter,
param,
createGroup,
} from "type-route";
const user = defineRoute(
{
userId: param.path.string,
},
(p) => `/users/${p.userId}`
);
const { routes } = createRouter({
home: defineRoute("/"),
about: defineRoute("/about"),
user,
userSettings: user.extend("/settings"),
userActivity: user.extend("/activity"),
});
// Create a group for all user-related routes
const groups = {
user: createGroup([routes.user, routes.userSettings, routes.userActivity]),
};
type PageProps = {
route: Route<typeof routes>;
};
function Page(props: PageProps) {
const { route } = props;
if (route.name === "home") {
return <div>Home</div>;
}
if (route.name === "about") {
return <div>About</div>;
}
// Use .has() to check if the route belongs to the user group
if (groups.user.has(route)) {
return <UserPage route={route} />;
}
return <div>Not Found</div>;
}
type UserPageProps = {
route: Route<typeof groups.user>;
};
function UserPage(props: UserPageProps) {
const { route } = props;
let pageContents;
if (route.name === "user") {
pageContents = <div>Main</div>;
} else if (route.name === "userSettings") {
pageContents = <div>Settings</div>;
} else if (route.name === "userActivity") {
pageContents = <div>Activity</div>;
}
return (
<>
<div>User Id: {route.userId}</div>
{pageContents}
</>
);
}