T
TanStack8mo ago
extended-salmon

Handling Both Dynamic and Index Route in one file

I have a file-based route
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => {
return fetchPost(params.postId)
},
})
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => {
return fetchPost(params.postId)
},
})
This works for /posts/$postId, but I want it to also cover /posts without creating a separate index route. I want to do it that way because /posts/$postIdand /posts will use the same component. The closest concept I can think of to what I want to achieve is the Optional Catch-all Segments feature in Next.js. Alternatively, I could move the component to a separate file and reuse it in both routes (index and dynamic). Is that the right approach?
1 Reply
extended-salmon
extended-salmonOP8mo ago
Renaming the file to $.index.tsx resolved my use case ($.tsx also works). If anyone spots an issue with this approach, please share your feedback. I’ll update this thread if any problems arise from using this method.

Did you find this page helpful?