To set up TanStack Router manually in a React project, follow the steps below. This gives you a bare minimum setup to get going with TanStack Router using both file-based route generation and code-based route configuration:
Using File-Based Route Generation
Install the necessary core dependencies:
Loading...
Install the necessary development dependencies:
Loading...
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
// Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
react(),
// ...,
],
})
If you are not using Vite, or any of the supported bundlers, you can check out the TanStack Router CLI guide for more info.
Create the following files:
- src/routes/__root.tsx (with two '_' characters)
- src/routes/index.tsx
- src/routes/about.tsx
- src/main.tsx
Loading...
Regardless of whether you are using the @tanstack/router-plugin package and running the npm run dev/npm run build scripts, or manually running the tsr watch/tsr generate commands from your package scripts, the route tree file will be generated at src/routeTree.gen.ts.
If you are working with this pattern you should change the id of the root <div> on your index.html file to <div id='root'></div>
Using Code-Based Route Configuration
The following example shows how to configure routes using code, and for simplicity's sake is in a single file for this demo. While code-based generation allows you to declare many routes and even the router instance in a single file, we recommend splitting your routes into separate files for better organization and performance as your application grows.
Loading...
If you glossed over these examples or didn't understand something, we don't blame you, because there's so much more to learn to really take advantage of TanStack Router! Let's move on.