Creating a custom 404 NotFound Page with React Routers

A 404 error is an HTTP status code that occurs webpage you try to reach a page that could not be found on the server. While the client may have been able to communicate with the server via get request, the server was unable to find the information that was requested.

Users can be extremely frustrated when reaching a 404 page. Creating a custom 404 page to redirect the user to a working page is a great way to improve the user experience. We will be going over how to create custom 404 page with react components and react routes.

In App.Js. Set up routes with React Router assigning different endpoints to different components. Create a wild card path with an asterisk(‘*’) and add it as the very last path.

import { Route, Switch, BrowserRouter } from 'react-router-dom';
import SplashPage from './login/SplashPage.jsx';
import NotFound from './NotFound.jsx';
const App = () => (
<BrowserRouter>
<Switch>
<Route exact path='/' component={SplashPage}/>
<Route path="*" component={NotFound} />
</Switch>
</BrowserRouter>
);
export default App;

NotFound.jsx

This is the fun part! Create a custom NotFound component and feel free to style it to fit your needs or create a custom PNG image that you can import.

import React from 'react';
import { Link } from 'react-router-dom';
import PageNotFound from '../assets/images/PageNotFound';
const NotFound = () => (
<div>
<img src={PageNotFound} style={{width: 400, height: 400, display: 'block', margin: 'auto', position: 'relative' }} />
<center><Link to="/">Return to Home Page</Link></center>
</div>
);
export default NotFound;

Finally remember to create a get request in your server.js. Whenever a user goes to a random page. The server should redirect the user back to the client so the routes can take over from there.

app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './index.html'));
});

Happy Coding!

Like what you read? Give Rose Espiritu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.