Nested route group navigation
I have the following file-based structure:
I have a few questions:
1. How can I set a default tab to be navigated to? My current solution is to directly link to
tab-a
from /user/$id/route.tsx
. I know there's a Navigate
component and useNavigate
but I'm not sure what's best practice.
2. How can I access the tab (and sub-tab) id? For example, when the user refreshes the page, I want to navigate them to that tab (and have it be shown as active). My current solution is to split location.pathname
but it's not type-safe and it seems wonky.
Thank you!4 Replies
extended-salmon•14mo ago
1. You can use a redirect to set a default tab to head to.
- Create the file
src/routes/user/$id/index.tsx
- Throw a redirect in the beforeLoad
or loader
callbacks. throw redirect({ to: '/user/$id/tab-a, params: { id } })
2. Not sure I understand what you are trying to achieve here.
Please attach a reproduction.deep-jadeOP•14mo ago
1. That worked great, thank you.
2. Is there a hook (or best practice) to get (and match) path segments of the URL?
For example, say I have a
/user/$id/(user-tabs)/settings/(settings-tabs)/theme
path with the following (general) structure:
So for the example URL /user/22/settings/theme
, is there a way to get settings
and theme
in TanStack Router, such that I can display the tab as active
? I'm currently doing const currentTab = location.pathname.split("/").at(3);
for (user-tabs)
and const currentTab = location.pathname.split("/").at(4);
for (settings-tabs)
but that has some issues and isn't exactly type-safe.xenogeneic-maroon•14mo ago
can you please share a complete minimal example by forking one of the existing router examples on stackblitz?
e.g. https://tanstack.com/router/v1/docs/framework/react/examples/quickstart-file-based
React TanStack Router Quickstart File Based Example | TanStack Rout...
An example showing how to implement Quickstart File Based in React using TanStack Router.
deep-jadeOP•14mo ago
@Manuel Schiller Here's is a minimal example: https://stackblitz.com/edit/tanstack-router-tpes6k?file=src%2Froutes%2Fuser%2F%24userId%2Froute.tsx
Is my approach to creating these nested routes correct? I am using the
route.tsx
files as layouts. I find the documentation on layouts to be confusing.
I would like the retrieval of "tab names" (e.g., tab-a
, tab-b
, sub-tab-a
, and sub-tab-b
) to be type-safe, but my current approach is not. I don't know if this is possible in TanStack Router.
Also, as an extra question: is there a way to strongly type these tab definition paths without doing some complex TypeScript? For example, sub-tab-a
and sub-tab-b
are not strongly typed (obviously), but is that possible/best-practice in TanStack Router out-of-the-box?
avery
StackBlitz
Router Basic File Based Example (forked) - StackBlitz
Run official live example code for Router Basic File Based, created by Tanstack on StackBlitz