Reorganize File-Based Routes in Tanstack Router

In this lesson, we learn how to reorganize file-based routes in TanStack Router to accommodate nested routing structures.

We explore how to create additional nested routes by converting files into directories, allowing for further nesting.

For example, to create a nested route like /employees/$employeeId/edit, we can create a directory (!) named $employeeId and place an index.tsx file inside it to define the route component for this nested route.

This approach provides flexibility in organizing files while maintaining the convention that file names and locations align with route paths. We also see how to adapt existing components and loaders to work with these reorganized routes, enabling features like edit forms or delete actions (or whatever) within nested routes.

Share with a coworker

Transcript

[00:00] In file-based routing we need to follow the convention that the name and the location of the file needs to be aligned with what is exactly the root of a certain component. However, we still have some flexibility in how we organize the files. So let's say that here we would need to provide a employees slash employee ID and let's say that would be an edit create new or whatever a yet another nested root over here. So we cannot put essentially a file under a file, we would need to turn it into a directory. So in this case we could create a $employeeID which is essentially walking into the same piece of a nested root and the file that is going to be the root definition would be called index.tsx, the same as this welcome home component that we have over here.

[00:59] So let me just create this index.tsx file over here and I'm just going to quickly copy the content of our nested root file. So let me just walk into index.tsx and I'm just going to quickly paste this one over here. Now I need to import the function that does the HTTP call. And let's also remove the first one. So I'm going to remove the employees slash employee ID parameter.

[01:35] Now, this file is being correctly imported by the root tree again so as we can see over here there is the new location that is being imported from. And if we walk back to the file then we can just make sure that the application is correctly up and running. So Here walking into the employees we would see that the employee details are correctly displayed. Now this way we could also provide something like the edit form, update form, delete action, or whatever we need.