Optional Catch-all Segments in File Based routing
I know this concept from Next.js:
pages/shop/[[...slug]].ts
https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes#optional-catch-all-segments
What would the equivalent in Tanstack Router be with file based routing? Currently I have duplicate index and $ routes which can't be the right way of doing it.Routing: Dynamic Routes | Next.js
Dynamic Routes are pages that allow you to add custom params to your URLs. Start creating Dynamic Routes and learn more here.
7 Replies
painful-plumOP•2y ago
Anyone familiar with this?
xenial-black•2y ago
Have you tried splat routes?
https://tanstack.com/router/latest/docs/framework/react/guide/route-trees#splat--catch-all-routes
To be honest, I am not sure if they match for "index" routes, but you could try. (I have not used them myself.)
Route Trees & Nesting | TanStack Router Docs
Like most other routers, TanStack Router uses a nested route tree to match up the URL with the correct component tree to render.
To build a route tree, TanStack Router supports both:
painful-plumOP•2y ago
From my testing the splat route does not catch the index.
Say I have
files/$ that would capture /files/documents and files/documents/hello-world but NOT /files. Right?xenial-black•2y ago
I am not sure... 😉 never used them myself. It's not 100% clear in the docs. But if you tried it and it didn't work... probably not. Let me check...
painful-plumOP•2y ago
Yes I checked and couldn't get it to work. Entirely possible I'm the one that did something wrong since I just started using TanStack Router.
But I feel like that's a common pattern and I couldn't find an example anywhere online
xenial-black•2y ago
I just tried it. Indeed this seems to be missing right now.
What you can do: Add both
/foo/$.tsx and /foo/index.tsx and import the component from one file to the other.painful-plumOP•2y ago
Yep, that's what I'm doing at the moment. Definetly workable but I can't shake off the feeling that there must be a cleaner way
I'm gonna file an issue on the GitHub repo and see where this leads. Thanks for your help!