Blog>
Snippets

Setting Up Browser History in TanStack Router

Demonstrate how to configure TanStack Router to use browser history for navigation in a SPA, including defining routes and programmatically navigating between them.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
First, import the necessary modules from tanstack-router. createBrowserRouter for creating a router instance that uses the browser's history API and RouterProvider to incorporate the router throughout your application.
const router = createBrowserRouter([
  {
    path: '/',
    element: '<HomePage />',
    loader: () => import('./components/HomePage')
  },
  {
    path: '/about',
    element: '<AboutPage />',
    loader: () => import('./components/AboutPage')
  }
]);
Define your routes within the createBrowserRouter. Each route object can define a path, the component (element) to render, and optionally a loader function for lazy loading the component.
function App() {
  return (
    <RouterProvider router={router} />
  );
}
Wrap your application or a part of it with RouterProvider, passing the router instance you created. This allows the defined routes to become active and govern the rendering of components based on the URL path.
import { useNavigate } from 'tanstack-router';

function NavigationComponent() {
  const navigate = useNavigate();
  
  const goToAboutPage = () => navigate('/about');
  
  return <button onClick={goToAboutPage}>Go to About Page</button>;
}
Demonstrates how to programmatically navigate between routes using useNavigate hook. In this example, a function is defined to navigate to the '/about' route when a button is clicked.