T
TanStack12mo ago
like-gold

Index.tsx or Route.tsx

I'm struggling to understand the difference between these two. From the docs on route.tsx:
When using directories to organize your routes, the route suffix can be used to create a route file at the directory's path. For example, blog.post.route.tsx or blog/post/route.tsx can be used at the route file for the /blog/post route.
and the index.tsx description:
Routes segments ending with the index token (but before any file types) will be used to match the parent route when the URL pathname matches the parent route exactly.
this sounds like it's doing the same to me
1 Reply
passive-yellow
passive-yellow12mo ago
Let me try and break it down of you. Say that you are visiting /posts/ When you have a posts.tsx/posts.route.tsx file, the component tree looks like this.
<RootRoute>
<PostsRoute />
</RootRoute>
<RootRoute>
<PostsRoute />
</RootRoute>
Now, if you had a posts.index.tsx file, the tree would look like this.
<RootRoute>
<PostsIndex />
</RootRoute>
<RootRoute>
<PostsIndex />
</RootRoute>
On the surface, they both seem to be the quite similar. But where it differs is that the .route.tsx file is somewhat like a shared layout. So, lets say that we have the following routes - /posts/ - /posts/$postId If you used the posts.tsx/posts.route.tsx file, in combination with a posts.index.tsx file, your tree would look like this when visiting /posts/.
<RootRoute>
<PostsRoute>
<PostsIndex />
</PostsRoute>
</RootRoute>
<RootRoute>
<PostsRoute>
<PostsIndex />
</PostsRoute>
</RootRoute>
This matters because, that means that the posts.tsx/posts.route.tsx file's content will also be present on when you get to the posts.index.tsx file. So, if you were to visit /posts/123 -> /posts/$postId, your tree would look like this.
<RootRoute>
<PostsRoute>
<PostIdRoute />
</PostsRoute>
</RootRoute>
<RootRoute>
<PostsRoute>
<PostIdRoute />
</PostsRoute>
</RootRoute>
With that explanation in hand, the route.tsx file in this instance can be considered to be somewhat similar to what Next does with its layout.tsx file. Where the component content in the file wraps whatever children proceed that route. Whereas in Next, you'd be rendering children recieved as a prop, in TSR you'd use the <Outlet /> component instead.
// nextjs
function Component({ children }: { children: React.ReactNode }) {
return (
<div>
<p>I'm shared content</p>
{children}
</div>
)
}

// TanStack Router
function Component() {
return (
<div>
<p>I'm shared content</p>
<Outlet />
</div>
)
}
// nextjs
function Component({ children }: { children: React.ReactNode }) {
return (
<div>
<p>I'm shared content</p>
{children}
</div>
)
}

// TanStack Router
function Component() {
return (
<div>
<p>I'm shared content</p>
<Outlet />
</div>
)
}
As a rule of thumb, use the index.tsx file, if your route could have other siblings, and route.tsx when you are building a layout.

Did you find this page helpful?