Create a new Route in Tanstack Router

In this lesson, we learn how to create a new route in TanStack Router by simply adding a new file to the routes directory.

For example, creating an employees.tsx file automatically generates a new route, which is reflected in the routeTree.gen.tsx file.

We explore how to define the root component within this new file and how to link to it from other components using the <Link> component.

The lesson highlights the benefits of type safety provided by TypeScript, which helps catch typos and ensures that only valid routes are used. This approach streamlines the process of adding new routes and maintaining a robust routing system.

Share with a coworker

Transcript

[00:00] Let's create a new root by creating simply a new file inside the roots directory Now we're going to display a list and details of some employee objects, whatever but we're just simply going to create a new employees file and please take a look that I have just created this empty file, employees.tsx, and the whole thing has been created for me. Now if we take a look at the root.regen file we will see that besides the index root and the about root there is also a new piece the employees root so this all has been automatically generated for us. Now if we walk back into the employees TSX we will see that there is a very similar create file root declaration, very similar to the ones that we have seen before we'll be able to compare it with the about one and there is also a root component which in this case we could rename to employees component whatever and here what the test accruer expects is that we will tell it what is the root over here and what is going to be the component. So by default, these two things, the root declaration and the component reside in the same file and there is no need to tear them apart.

[01:19] So if we run this and if we reload the application we will see that nothing has changed because we also need to walk back into the main root component and what we can do is simply to use what we've had before and Create a new link. So here the link is going to Move to employees Now if you take a closer look, we can walk up, but this is IntelliSense. So this is not something I have configured in this IDE. This is TypeScript already running, right? So these are the available routes that I can walk into.

[02:03] So in other words, if I put something like this, this is a typo, but this is going to be figure out by TypeScript. So how does this work? Again, if we walk back into root.regen file, we would see that, hey, like these are the ones that are available so if I accidentally or deliberately made a typo this is just going to not compile right so let's just put that This is going to be an employees one. And yep, home, about and the new employees. Hello slash employees.