Blog>
Snippets

Setting up TanStack Router in a React Project

Demonstrate the installation and basic setup of TanStack Router in a new React project, including the initialization of the router and a simple route configuration.
// Step 1: Install TanStack Router via your terminal
// npm install @tanstack/react-location
This line isn't code but a command to be run in your terminal to install the TanStack Router package.
import { ReactLocation, Router } from '@tanstack/react-location';
import { Home } from './Home';
import { NotFound } from './NotFound';
Imports ReactLocation and Router from the TanStack package, and also Home and NotFound components for the routes.
const location = new ReactLocation();
Initializes the ReactLocation instance required by the Router.
const routes = [
  { path: '/', element: <Home /> },
  { path: '/*', element: <NotFound /> }
];
Defines the routes for the application. A root route for Home component and a wildcard route for NotFound.
function App() {
  return (
    <Router location={location} routes={routes} />
  );
}
Sets up the Router in the App component with the initialized location and defined routes.