Blog>
Snippets

Basic Setup of TanStack Router in a React Application

Illustrate the initial steps to install and configure TanStack Router in a React project, demonstrating how to set up a simple routing with a homepage and an about page.
npm install @tanstack/react-router
First, install the TanStack Router package using npm or your preferred package manager.
import { createBrowserRouter, RouterProvider, Outlet } from '@tanstack/react-router';
import ReactDOM from 'react-dom/client';
import React from 'react';

// Define your components
function Home() {
  return <div><h2>Home Page</h2></div>;
}

function About() {
  return <div><h2>About Page</h2></div>;
}

// Create the router
const router = createBrowserRouter([
  { path: '/', element: <Home/>, errorElement: <div>Not Found</div> },
  { path: '/about', element: <About/>, errorElement: <div>Not Found</div> }
]);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);
This code snippet shows how to set up TanStack Router in a React application. We define two components, 'Home' and 'About', to serve as pages. Then, we create a router with routes to these components. Each route is defined with a path and an element to render. Finally, we wrap our app in the 'RouterProvider' to make the router active.