Blog>
Snippets

Basic TanStack Router Setup

Shows how to set up TanStack Router in a React project, including installing the router package and configuring the root component with routes.
// Step 1: Install TanStack Router package
// npm install @tanstack/react-location
First, you need to install the TanStack Router package. This example uses npm for package management.
import { ReactLocation, Router } from '@tanstack/react-location';
import { Home, About, NotFound } from './pages'; // Import your page components
Import the necessary modules from @tanstack/react-location and your page components.
// Step 2: Create a ReactLocation instance
const location = new ReactLocation();
Create an instance of ReactLocation. This handles the location state and history for your routes.
// Step 3: Define your routes
const routes = [
  { path: '/', element: <Home /> },
  { path: 'about', element: <About /> },
  { path: '*', element: <NotFound /> }
];
Define your application routes. Each route is an object containing a path and the component (element) to render.
// Step 4: Set up the Router in your app's component structure
function App() {
  return (
    <Router routes={routes} location={location}>
      {/* Your app's structure goes here, the Router will render matched routes */}
    </Router>
  );
}
Integrate the Router into your app by wrapping your application or the relevant part of it with the Router component, passing the routes and location instance.