T
TanStack•2y ago
painful-plum

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-plum
painful-plumOP•2y ago
Anyone familiar with this?
xenial-black
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-plum
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
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-plum
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
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-plum
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!

Did you find this page helpful?