Blog>
Snippets

Custom 404 Error Page Rendering with TanStack Router

Illustrates how to render a custom 404 error page using TanStack Router when a user navigates to an undefined path, enhancing the overall appearance of error messages.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
import React from 'react';
import ReactDOM from 'react-dom';
import YourCustom404Page from './YourCustom404Page'; // Make sure to create this component
import HomePage from './HomePage'; // Your home page component
First, import necessary components from 'react-router-dom' along with React, ReactDOM, and your custom pages.
const router = createBrowserRouter([
  {
    path: '/',
    element: <HomePage />,
  },
  {
    path: '*',
    element: <YourCustom404Page />,
  },
]);
Create a router with the 'createBrowserRouter' function, defining routes for the homepage and a wildcard '*' path for undefined routes leading to your custom 404 page.
ReactDOM.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
  document.getElementById('root')
);
Render your app with 'RouterProvider' passed the 'router' as a prop, which incorporates your custom 404 error handling.