Create 404 page in react

To create a 404 page in React using React Router, create a wildcard path with an asterisk(‘*’) and add it to the very last path of our routes.

A 404 page is a user sees when they try to load a non existing URL on our site. This may be because of user clicked on a broken link or they have mistyped a URL. We can provide useful navigation or links on the 404 page which helps the user continue on the website.

React Router is used to map URL paths to React components. We are going to implement a 404 page using React Router.

We have two methods to set up 404 page in React.

  1. 404 page using a wildcard path with an asterisk(‘*’)
  2. Redirect to the sitename.com/404 path

Before going to start, Install React Router in the React project using the below command.

npm install [email protected]

404 page using a wildcard path with an asterisk(‘*’)

Show Page Not Found content in the requested URL is the best way to handle 404 requests. For this use wildcard path with an asterisk(*) at the end of the routes. Using * renders the PageNotFound component for all the URLs not specified in the routes. Let us explain with below sample code.

Note: Before using the below code, please make sure you are using React Router V6 or the latest version.

import React from 'react';
import {Route, Link, Routes} from 'react-router-dom';

export default function App() {
  	return (
    	<>      
        	<nav>
          		<ul>
            		<li>
              			<Link to="/">Home</Link>
            		</li>
					<li>
              			<Link to="/contact">Contact</Link>
            		</li>
          		</ul>
        	</nav>

	
        	<Routes>
          		<Route path="/" element={<Home />} />
		  		<Route path="/contact" element={<Contact />} />
          		<Route path="*" element={<PageNotFound />} />
        	</Routes>
    	</>
  	);
}

function Home() {
  	return <p>Home</p>;
}

function Contact() {
	return <p>Contact</p>;
  }

function PageNotFound() {
  	return (
    	<div>
      		<p>404 Page not found</p>
    	</div>
  	);
}

If a user navigates to / or /contact, the corresponding component that we set for the routes, will get rendered. however, if a user navigates to any non existing URLs, the PageNotFound component will be rendered. Because we have given <Route path="*" element={<PageNotFound />} /> at the end of routes to catch no matching route in the routes list.

Redirect to sitename.com/404 path

Here we are redirecting the user to another page(in the below example we are redirecting to the home page) instead of rendering the PageNotFound component. For this, we are using Navigate component imported from the react-router-dom. Given below is a sample code for implementing this.

import React from 'react';
import {Route, Link, Routes, Navigate} from 'react-router-dom';

export default function App() {
  return (
    <>      
        <nav>
          	<ul>
            	<li>
              		<Link to="/">Home</Link>
            	</li>
			    <li>
              		<Link to="/contact">Contact</Link>
            	</li>           
	
          	</ul>
        </nav>

        <Routes>
          	<Route path="/" element={<Home />} />
		    <Route path="/contact" element={<Contact />} />
		    <Route path="/404" element={<PageNotFound />} />
          	<Route path="*" element={<Navigate to="/404" />} />
        </Routes>
    </>
  );
}

function Home() {
  	return <p>Home</p>;
}

function Contact() {
	return <p>Contact</p>;
}

function PageNotFound() {
  	return (
    	<div>
      		<p>404 Page not found</p>
    	</div>
  	);
}

Conclusion

To implement a 404 page not found in the react application with React Router, use a wildcard path with an asterisk(‘*’) and add it to the very last path of our routes with <PageNotFound/> as the element. Or we can redirect to sitename.com/404 path using the Navigate component imported from the react-router-dom.

Related Blogs

Can't Perform a React State Update on an Unmounted Component

Can't Perform a React State Update on an Unmounted Component

React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted. Explains how to fix it.

Each child in a list should have a unique key prop

Each child in a list should have a unique key prop

Solve Warning: Each child in a list should have a unique ”key" prop in React by setting the id property as a unique key or by auto-assigning unique keys.

React Hook is Called Conditionally

React Hook is Called Conditionally

Error: "React Hook is called conditionally. React Hooks must be called in the exact same order in every component render" occurs when hooks are invoked conditionally or after a return of a value.

Too many re-renders. React limits the number of renders to prevent an infinite loop

Too many re-renders. React limits the number of renders to prevent an infinite loop

The React error "Too many re-renders. React limits the number of renders to prevent an infinite loop" happens when you have reached an infinite render loop.

Adjacent JSX elements must be wrapped in an enclosing tag

Adjacent JSX elements must be wrapped in an enclosing tag

The "Adjacent JSX elements must be wrapped in an enclosing tag" error can be solved by wrapping the multiple elements in a parent div or in a react fragment

The tag is unrecognized in this browser

Warning: The tag is unrecognized in this browser

Warning "The tag is unrecognized in this browser" occurs when the tag doesn't exist in the browser or when we render a component starting with a lowercase letter.

The style prop expects a mapping from style properties to values, not a string

The style prop expects a mapping from style properties to values, not a string

"The style prop expects a mapping from style properties to values, not a string" React error occurs when we pass a CSS string to the style attribute.

Pass event and parameter onClick in React

How to pass event and parameter onClick in React

We set the inline arrow function (event) => clickHandler(event, "Hello World!") as props to the onClick event handler in the button. The arrow function takes the event as an argument and calls the clickHandler function.

Create a Back button with React Router

Create a Back button with React Router

To create a back button with React Router use useNavigate() hook. Call navigate function eg. navigate(-1); inside the onClick function of the back button.