If you have an extensive web application that generates dynamic routes, then it would be helpful to show them a 404 page when the page does not exist or is broken.
Handling 404 Not Found pages is essential in web applications because it tells users that what they are looking for here on this app does not exist for a better user experience.
404 pages are also important for search engines like Google because this tells search engines that the page does not exist, so they do not index invalid content.
Overview
In this project, we will create a small project using TanStack Router, MUI for styling, and Vite for React. We will focus on handling 404 Not Found pages. I’ll use a modular approach with reusable components.
Here is the step-by-step guide:
Step 1: Setup a Vite project with a React template
Let’s set up the project and install dependencies:
npm create vite@latest tanstack-router-404 -- --template react cd tanstack-router-404 npm install
Install the third-party libraries using the below command:
npm install @tanstack/react-router @mui/material @emotion/react @emotion/styled
Step 2: Setup Layout component
Under the “src” folder, create a new folder called “components”, and inside that folder, create a new file called “Layout.jsx” and add the code below in it:
// src/components/Layout.jsx import { AppBar, Toolbar, Typography, Container, Box } from '@mui/material' import { Link } from '@tanstack/react-router' export default function Layout({ children }) { return ( <Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}> <AppBar position="static"> <Toolbar> <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}> My App </Typography> <Link to="/" style={{ color: 'white', marginRight: '1rem' }}>Home</Link> <Link to="/about" style={{ color: 'white' }}>About</Link> </Toolbar> </AppBar> <Container component="main" sx={{ mt: 4, mb: 4, flex: '1 0 auto' }}> {children} </Container> <Box component="footer" sx={{ py: 3, px: 2, mt: 'auto', backgroundColor: 'background.paper' }}> <Typography variant="body2" color="text.secondary" align="center"> © 2024 My App </Typography> </Box> </Box> ) }
Step 3: Setup a 404 component or page
So, when a user types a different URL that does not exist in our application, we will display this component.
Under the components folder, create a new file called “NotFound404.jsx” and add the code below:
// src/components/NotFound404.jsx import { Typography, Button, Box } from '@mui/material' import { Link } from '@tanstack/react-router' export default function NotFound404() { return ( <Box sx={{ textAlign: 'center', mt: 8 }}> <Typography variant="h1" component="h1" gutterBottom> 404 </Typography> <Typography variant="h4" component="h2" gutterBottom> Page Not Found </Typography> <Typography variant="body1" paragraph> The page you are looking for doesn't exist or has been moved. </Typography> <Button component={Link} to="/" variant="contained" color="primary"> Go to Home </Button> </Box> ) }
Step 4: Create Home and About components
Under the components folder, create the following two new components:
- Home.jsx
- About.jsx
Here is the code for Home.jsx:
// src/components/Home.jsx import { Typography } from '@mui/material' export default function Home() { return ( <Typography variant="h4" component="h1" gutterBottom> Welcome to the Home Page </Typography> ) }
Here is the code for About.jsx:
// src/components/About.jsx import { Typography } from '@mui/material' export default function About() { return ( <Typography variant="h4" component="h1" gutterBottom> About Us </Typography> ) }
Step 5: Setup Routing
I already wrote a detailed guide on how to integrate TanStack Router in React on this website. Feel free to checkout and understand why this library is helpful.
Under the “src” folder, create a new file called router.js and add the code below:
// src/router.js import { createRouter, createRoute, createRootRoute } from '@tanstack/react-router' import App from './App' import Home from './components/Home' import About from './components/About' import NotFound404 from './components/NotFound404' const rootRoute = createRootRoute({ component: App, }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: Home, }) const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', component: About, }) const notFoundRoute = createRoute({ getParentRoute: () => rootRoute, path: '*', component: NotFound404, }) const routeTree = rootRoute.addChildren([indexRoute, aboutRoute, notFoundRoute]) export const router = createRouter({ routeTree })
In this code, we defined notFoundRoute. It defines a catch-all route for handling 404 Not Found errors.
In the path property, we set it to “*” which means this “*” path matches any URL that does not match the previously defined routes.
In short, if a user hits a URL path that does not match an already defined path, it matches this “*” path, and it will show the NotFound404 component.
This setup ensures the application has a structured routing mechanism, properly handling different paths, including a catch-all route for 404 Not Found.
Step 6: Update the App component
Here is the updated code for the src/App.jsx file:
// src/App.jsx import { Outlet } from '@tanstack/react-router' import Layout from './components/Layout' export default function App() { return ( <Layout> <Outlet /> </Layout> ) }
Step 7: Update the entry point main.jsx component
Here is the updated code for the src/main.jsx file:
// src/main.jsx import { StrictMode } from 'react' import ReactDOM from 'react-dom/client' import { RouterProvider } from '@tanstack/react-router' import { router } from './router' ReactDOM.createRoot(document.getElementById('root')).render( <StrictMode> <RouterProvider router={router} /> </StrictMode> )
Our final project structure looks like this:
src/ components/ Layout.jsx NotFound404.jsx Home.jsx About.jsx router.js App.jsx main.jsx
Step 8: Run the project
To run a Vite project, use the “npm run dev” command in your terminal:
Go to the browser and type this URL: http://localhost:5173/
If you click on the About link, you will be able to see the About page like this:
Now is the time to check out the 404 page.
Type this URL in the browser: http://localhost:5173/new-post
That’s all!