Setting Up TanStack File-Based Router with a Vite React App
Tags: react, tanstack, vite, projects
Published: 2024-06-30 05:44:48

---
title: Setting Up TanStack File-Based Router with a Vite React App
published: true
date: 2024-06-23 18:46:19 UTC
tags: React,tanstack,vite,projects
canonical_url: https://iamdipankarpaul.hashnode.dev/setting-up-tanstack-file-based-router-with-a-vite-react-app
---

Integrating a file-based router in your Vite React application can streamline your development process by allowing you to organize your routes in a simple, intuitive manner. TanStack's file-based router is an excellent choice for this task. In this blog post, I'll guide you through the process of setting up TanStack File Router in a Vite React app.

## Step 1: Set Up a Vite React Project

First, we need to create a new Vite React project. If you already have a Vite React project, you can skip this step.

### Create a new Vite React project

```sh
    npm create vite@latest my-react-app -- --template react
    cd my-react-app
```

### Install dependencies

```sh
    npm install
```

## Step 2: Install TanStack Router

Next, we need to install the TanStack Router.

### Install TanStack Router

```sh
    npm install @tanstack/react-router
```

### Install the Vite Plugin and the Router Devtools

```sh
    npm install --save-dev @tanstack/router-plugin @tanstack/router-devtools
```

### Configure the Vite Plugin

```js
   import {
       defineConfig
   } from "vite";
   import react from "@vitejs/plugin-react";
   import {
       TanStackRouterVite
   } from "@tanstack/router-plugin/vite";

   // https://vitejs.dev/config/
   export default defineConfig({
       plugins: [TanStackRouterVite(), react()],
   });
```

## Step 3: Set Up the File-Based Router

Now, let's set up the file-based router by creating the necessary directory structure and defining our routes.

### Create the directory structure

   - Create a `routes` folder insie `src` folder of your project.
   - Inside the `routes` folder, create your route components and structure them according to your needs.
   - Follow Tanstack Router [guide-lines](https://tanstack.com/router/latest/docs/framework/react/guide/file-based-routing#file-naming-conventions).

### Example directory structure

```
 src
 ┣ routes
 ┃ ┣ about.lazy.jsx
 ┃ ┣ index.lazy.jsx
 ┃ ┣ posts.jsx
 ┃ ┗ __root.jsx
 ┣ App.jsx
 ┣ index.css
 ┣ main.jsx
 ┗ routeTree.gen.ts
```

> Route files with the `.lazy.tsx` extension are lazy loaded via separate bundles to keep the main bundle size as lean as possible.

### Define the routes

#### src/routes/__root.jsx

```jsx
import { createRootRoute, Link, Outlet } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/router-devtools";
        
// It's the layout component
export const Route = createRootRoute({
  component: () => (
    <>
      <div className="p-2 flex gap-2">
         <Link to="/" className="[&.active]:font-bold">
           Home
         </Link>{" "}
         <Link to="/about" className="[&.active]:font-bold">
           About
         </Link>
         <Link to="/posts" className="[&.active]:font-bold">
           Posts
         </Link>
       </div>
       <hr />
       <Outlet />
       <TanStackRouterDevtools />
     </>
    ),
});
```

#### src/routes/index.lazy.jsx

```jsx
import { createLazyFileRoute } from "@tanstack/react-router";

export const Route = createLazyFileRoute("/")({
  component: Index,
});
        
function Index() {
  return (
    <div className="p-2">
      <h3>Welcome Home!</h3>
    </div>
  );
}
```

#### src/routes/about.lazy.jsx

```jsx
import { createLazyFileRoute } from "@tanstack/react-router";

export const Route = createLazyFileRoute("/about")({
  component: About,
});
        
function About() {
  return <div className="p-2">Hello from About!</div>;
}
```

#### src/routes/posts.jsx

```jsx
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/posts")({
  component: Posts,
});
        
function Posts() {
  return (
    <div className="p-2">
      <h3>Hello from Post!</h3>
    </div>
  );
}
```

### Configure the router in App.jsx

```jsx
import { RouterProvider, createRouter } from "@tanstack/react-router";
// Import the auto generated route tree
import { routeTree } from "./routeTree.gen";
        
// Create a new router instance
const router = createRouter({ routeTree });
        
export default function App() {
  return (
    <>
      <RouterProvider router={router} />
    </>
  );
}
```

> `src/routeTree.gen.ts` file will be autometically generated.

## Step 4: Run Your Application

With everything set up, it's time to run your application.

### Start the development server

```sh
    npm run dev
```

Open your browser and navigate to `http://localhost:5173/` . You should see your Vite React application running with TanStack Router handling the routes.

To add more routes, simply create new components in the `routes` directory and configure them in the `__root.jsx` file as needed.

By following these steps, you can efficiently set up a file-based router in your Vite React application using TanStack Router. This setup not only simplifies route management but also enhances the organization and scalability of your project.