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•12mo 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.
Now, if you had a posts.index.tsx
file, the tree would look like this.
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/
.
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.
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.
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.