T
TanStack7mo ago
other-emerald

Set default child route

Hello, I already have a solution working for this, but I'm just checking to see if there's a better way to do what I'm trying to do here, or if I shouldn't be trying to do this at all and I should be using a different structure. Lets say for an example my site has pages for "groups", with subpages to view a group's members and to view posts made within the group. There is no page for just the group itself, only these views of either the members or posts, and one must always be selected. To model this via the router, I have a parent route group.$id and the child routes group.$id.$members and group.$id.posts. When a user navigates to just https://example.com/group/123 in their browser, I have it set up to automatically redirect them to a "default" child route, such as https://example.com/group/123/posts. To do this, I check in group.$id's beforeLoad function for if it is the "leaf" of the URL, as in the current route is none of its children, since the beforeLoad also runs for all of the child routes. If it is the current leaf route, I throw redirect({ to: "/group/$id/posts", params }) to redirect the user automatically. I wrote a custom function to detect if the current route is the left or not as shown below:
export function isLeaf(matches: MakeRouteMatchUnion<AnyRouter>[], route: AnyRoute): boolean {
return matches.at(-1)?.fullPath === route.id;
}

// use it as so...
beforeLoad: ({ matches, params }) => {
if (isLeaf(matches, Route)) {
throw redirect(/* ... */);
}
},
export function isLeaf(matches: MakeRouteMatchUnion<AnyRouter>[], route: AnyRoute): boolean {
return matches.at(-1)?.fullPath === route.id;
}

// use it as so...
beforeLoad: ({ matches, params }) => {
if (isLeaf(matches, Route)) {
throw redirect(/* ... */);
}
},
Is this how I should be going about this, or is there a better way?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?