Tanstack Router is an alternative to React Router.
For simplicity, we will create a Vite + React project from scratch:
1 | npm create vite@latest tanstack-router-demo -- --template react-ts |
This command will create a folder tanstack-router-demo for your demo project and install all dependency packages, finally start the server at http://localhost:5173 automatically.
Then install TanStack Router:
1 | npm install @tanstack/react-router |
At the time of writing, the latest @tanstack/react-router version is 1.143.6.
Set up project structure
1 | src/ |
src/routes/__root.tsx
This file defines the app layout.
1 | import { createRootRoute, Outlet, Link } from "@tanstack/react-router"; |
src/routes/index.tsx
1 | import { createFileRoute } from "@tanstack/react-router"; |
src/routes/posts.$id.tsx
1 | import { createFileRoute } from "@tanstack/react-router"; |
src/main.tsx
1 | import React from "react"; |
Generate the route tree
TanStack Router needs to scan your routes/ folder.
Run once:
1 | npx @tanstack/router-cli generate |
It creates:
1 | src/routeTree.gen.ts |
Re-run the command whenever you add/remove routes.
Start the app
1 | npm run dev |