T
TanStack3mo ago
magic-amber

How to setup the index of a Layout file?

Hey, guys! First of all I am new to Tanstack Router, although I have read pretty much all the documentation at this point. I am migrating my project from React Router to Tanstack Router. I previously had this set-up:
{
path: "settings",
element: <SettingsPage />,
children: [
{ index: true, element: <Navigate to="account" /> },
{ path: "account", element: <AccountSettingsPage /> },
{ path: "categories", element: <CategorySettingsPage /> },
{ path: "notifications", element: <NotificationSettingsPage /> },
],
}
{
path: "settings",
element: <SettingsPage />,
children: [
{ index: true, element: <Navigate to="account" /> },
{ path: "account", element: <AccountSettingsPage /> },
{ path: "categories", element: <CategorySettingsPage /> },
{ path: "notifications", element: <NotificationSettingsPage /> },
],
}
My <SettingsPage/> component is a layout file and I explicitly define an index route for it with index:true to navigate to /settings/account . I am not sure how to do this with Tanstack Router using file-based routing. The idea behind it is to guarantee users navigating to /settings won't see a blank page, but instead their account settings. Bacause it is their account settings we really want to keep the URL as /settings/account . My current setup with Tanstack is:
├── routes
│ ├── settings
│ │ ├── account.tsx
│ │ ├── categories.tsx
│ │ ├── notifications.tsx
│ │ ├── route.tsx //Layout file
├── routes
│ ├── settings
│ │ ├── account.tsx
│ │ ├── categories.tsx
│ │ ├── notifications.tsx
│ │ ├── route.tsx //Layout file
And in route.tsx I am trying to do this:
export const Route = createFileRoute("/settings")({
component: RouteComponent,
beforeLoad: () => {
redirect({
to: "/settings/account",
});
},
});

function RouteComponent() {
return (
<Card>
<h1>Hello "/settings"!</h1>
<Outlet />
</Card>
);
}
export const Route = createFileRoute("/settings")({
component: RouteComponent,
beforeLoad: () => {
redirect({
to: "/settings/account",
});
},
});

function RouteComponent() {
return (
<Card>
<h1>Hello "/settings"!</h1>
<Outlet />
</Card>
);
}
But that does not work, when I try to go to /settings the whole chrome tab halts. All help is highly appreciate it!
3 Replies
vicious-gold
vicious-gold3mo ago
you need to throw the redirect, but not from the route.tsx you need to add an index.tsx and throw the redirect there btw, you could also render a <Navigate> as the route component of index.tsx but throwing a redirect is definitely the better option
magic-amber
magic-amberOP3mo ago
Makes sense, thank you! Also, that explains why the website was haulting, since the redirect is in the layout route and that is always rendered, the redirect was called over and over.
vicious-gold
vicious-gold3mo ago
yep, infinite loop

Did you find this page helpful?