How to create custom 404 error page in react js

How to create custom 404 error page in react js

·

4 min read

A 404 page is what a user sees when they try to reach a non-existent page on your site (because they’ve clicked on a broken link, the page has been deleted, or they’ve mistyped a URL).

I am assuming you are using React Router. You have two options to show page not found component

  1. Redirect to yoursite.com/404
  2. Show Page not found content with requested URL.

Redirect to yoursite.com/404

In Order to redirect you need to import Redirect from “react-router-dom”. Place the redirect code at the very last path of your routes.

Now you App.jsx look like

import React from "react";
import { Redirect, Route, Switch, BrowserRouter } from 'react-router-dom';
import HomePage from './pages/HomePage.jsx';
import NotFoundPage from './NotFoundPage.jsx';
class App extends React.Component {
    render(){
        return(
            <BrowserRouter>
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route path="/404" component={NotFoundPage} />
                    <Redirect to="/404" />
                </Switch>
            </BrowserRouter>
        )
    }
}

export default App;

Show Page not found content with requested URL

Showing Page not found content with requested URL is actually good as my point of view. In order to use that you may use wildcard routes. Create a wildcard path with an asterisk(‘*’) and add at the very last path of your routes.

Now you App.jsx look like

import React from "react";
import { Redirect, Route, Switch, BrowserRouter } from 'react-router-dom';
import HomePage from './pages/HomePage.jsx';
import NotFoundPage from './NotFoundPage.jsx';
class App extends React.Component {
    render(){
        return(
            <BrowserRouter>
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route path="*" component={NotFoundPage} />
                </Switch>
            </BrowserRouter>
        )
    }
}

export default App;

NotFoundPage component

Not found page component is actually showcasing to show your creativity. You can create your own custom 404-page design.

import React from 'react';
import { Link } from 'react-router-dom';
import PageNotFound from '../assets/images/PageNotFound';
class NotFoundPage extends React.Component{
    render(){
        return <div>
            <img src={PageNotFound}  />
            <p style={{textAlign:"center"}}>
              <Link to="/">Go to Home </Link>
            </p>
          </div>;
    }
}
export default NotFoundPage;

I recommend visiting the following page to get inspiration for your awesome 404 pages.

Happy coding👩‍💻👨‍💻