How to display 404 screen – react js

To display a 404 screen in a React.js application, you can create a component that represents the 404 page and render it when a route is not found. Here’s an example of how you can implement it:

  1. Create a NotFound component:
import React from 'react';

const NotFound = () => {
  return (
    <div>
      <h1>404 - Page Not Found</h1>
      <p>The page you are looking for does not exist.</p>
    </div>
  );
};

export default NotFound;
  1. Set up routing in your application (assuming you are using React Router):
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import NotFound from './NotFound';
import Home from './Home'; // Import your other components

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        {/* Add other routes for your application */}
        <Route component={NotFound} /> {/* This route will match if no other route is matched */}
      </Switch>
    </Router>
  );
};

export default App;

In the code above, the Switch component is used to render only the first Route that matches the current URL. By placing the NotFound component as the last Route inside the Switch, it will be rendered when none of the other routes match.

Make sure to import the necessary components and define the routes according to your application’s structure. You can customize the NotFound component to include any design or additional information you want to display on the 404 page.

Leave a Reply