Blog>
Snippets

Detecting Unrecognized Paths with TanStack Router

Demonstrates detecting unrecognized paths using TanStack Router and redirects to a 404 error page, improving user experience when a route is not found.
import { createBrowserRouter, RouterProvider, createRoutesFromElements, Route } from 'react-router-dom';
import NotFoundPage from './components/NotFoundPage';
import HomePage from './components/HomePage';
Imports the necessary components from react-router-dom, including our custom NotFoundPage and HomePage components.
const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path='/' element={<HomePage />} />
    <Route path='*' element={<NotFoundPage />} />
  )
);
Creates a browser router instance and defines routes, including a catch-all route (*) that renders the NotFoundPage component for unrecognized paths.
function App() {
  return <RouterProvider router={router} />;
}
Defines the App component that utilizes RouterProvider to handle routing based on the defined router instance.