T
TanStack2mo ago
other-emerald

Path params without route

Hi, Wasn't sure how to explain it shortly but essentially i have this file books.$bookId.pages.$pageNum.tsx and this route should work only as is. So books.$bookId should redirect to 404 page (or to the first page - books.$bookId.pages.1.tsx) Plus, how do I parse bookId and pageNum as number and where exactly should i parse it? how can i achieve this? Thank you
4 Replies
wee-brown
wee-brown2mo ago
This can be done by naming it books.$bookId.pages_.$pageNum This will treat it as one path. Alternatively you could add a redirect in the before load of the books route to automatically redirect to first book. For parsing to number, the route has a “params” key where you can give it a parse function, similar to validateSearch. On my phone at the moment so don’t have links/code blocks 😜
other-emerald
other-emeraldOP2mo ago
thanks for response. parse is giving me an error saying "Type 'number' is not assignable to type 'string'" . what am I doing wrong?
No description
other-emerald
other-emeraldOP2mo ago
i thought maybe I should do the conversion in the parent route, but in this case i dont have a route for books/. that's why i was trying to exclude them. about redirection: can you help me understand how i can redirect to other page if route matches /books/$bookId? where do I set up the redirect?
wee-brown
wee-brown2mo ago
I'm not certain on this, but I believe the params issue is that tanstack is making a route for $bookId in the background because it doesn't have an underscore. I am not certain you can have an underscore on a dynamic path segment, so you may need to structure your route like following (unless you want to go down virtual routes, but I think this will help with your second point).
.books_.$bookId.ts // purely there to parse the bookId, and to redirect if a direct match (instead of not found)
.books_.$bookId.pages_.$pageNum // parses pageNum and other functionality you have
.books_.$bookId.ts // purely there to parse the bookId, and to redirect if a direct match (instead of not found)
.books_.$bookId.pages_.$pageNum // parses pageNum and other functionality you have
To achieve the redirect, you need a route for $bookId directly, because you need something that the visitor can visit for you to know where to redirect them. You don't need to give this route a component, you can just have a beforeLoad that checks if it is a direct match (opts.matches.find(...)) and if so, then redirect them automatically. Otherwise a route doesn't exist and they get a 404.

Did you find this page helpful?