How to setup 404 page in React Routing ?
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:
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.
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.
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:
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.