Image by https://dribbble.com/kunchevsky

How to Creating a custom 404 Page with React Routers?

Naveen DA
2 min readDec 27, 2018

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).

Note: For v6, please refer this post:

https://medium.com/@naveenda/how-to-creating-a-custom-404-page-with-react-routers-v6-52efe2cd3807

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👩‍💻👨‍💻

  1. http://collectui.com/challenges/404-page
  2. https://dribbble.com/tags/404
  3. https://pinterest.com/search/pins/?q=404

--

--