Best way to avoid route duplication for optional parent segment (file-based routing)
I'm using file-based routing and need to support an optional parent segment in my URLs.
Current routes:
New requirement (without duplicating routes):
Since optional path params aren't supported, what’s the best way to reuse routes without duplicating all child configs (loader, beforeLoad, etc.)? Any recommended patterns for this?
Thanks! 🙏
5 Replies
quickest-silver•7mo ago
Move code that doesn't change if the parent param isn't present into it's own layout component(s). The code that's common to all loaders and before load, you can move into there own reuseable functions as well (you'll end up having to write a bit more type annotations as well).
You could look into https://tanstack.com/router/latest/docs/framework/react/routing/virtual-file-routes as well, I'm not too sure how well it would work for you.
Virtual File Routes | TanStack Router React Docs
We'd like to thank the Remix team for . We've taken inspiration from their work and adapted it to work with TanStack Router's existing file-based route-tree generation. Virtual file routes are a power...
rival-blackOP•7mo ago
Thanks for the tips! I tried the virtual routing approach but couldn't get it to work - maybe I'm doing it wrong!? 🤔
I set up a simple StackBlitz example (https://stackblitz.com/edit/tanstack-router-pbshsqaa), but it throws this error:
Any thoughts on what I might be missing?
national-gold•7mo ago
virtual route won't help here
rival-blackOP•7mo ago
@Manuel Schiller thanks for the clarification! If virtual routes won't help in this case, what approach would you recommend?
national-gold•7mo ago
you need separate route files until we support optiona path params