Open In App
Related Articles

How to setup 404 page in React Routing ?

Improve Article
Save Article
Like Article

Every Website needs a 404 page if the URL does not exist or the URL might have been changed. To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple react component called PagenotfoundComponent

Creating React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app 404page

Note: If you’ve previously installed create-react-app globally via npm, directly use the command below:

Your development environment is ready. Let us now install react-router in our Application.

Step 2: After creating your project folder i.e. styled, move to the same folder:

cd styled

Step 3:  Installing react-router-dom: react-router-dom can be installed via npm in your React application. Follow the steps given below to install react-router-dom in your React application: To install the react-router-dom use the following command:

 npm install --save react-router-dom

Project Structure: It will look like the following.

Project Structure

Step 4: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.



import React from "react";
import { Route, Switch, BrowserRouter }
    from 'react-router-dom'
import Home from '.Home';
import PageNotFound from './404Page';
function App() {
    return (
                <Route exact path='/' component={Home} />
                <Route path="*" component={PageNotFound} />
export default App;



import React from 'react';
const Home = () => {
        <h1>Home Page</h1>
export default Home;



import React from 'react';
const PageNotFound = () => {
        <h1>404 Error</h1>
        <h1>Page Not Found</h1>
export default PageNotFound;

Explanation: Here the route for PageNotFound is provided inside the routing. Here any path except the provided routes is handled by this PageNotFound and our HTML template is displayed in the browser. So now if someone tries to send a request to any page that is not present in the routes array then that user is automatically navigated to this PagenotfoundComponent.

Step to run the application: Run the following command to start the application:

npm start

Output: Now open the browser and go to http://localhost:3000, where everything is working fine. Now go to http://localhost:3000/anything, where we will get the 404 error as shown below.

Last Updated : 25 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials