What is the best way to handle a 404 page using React-Router

0 votes
With the help of code can you tell me What is the best way to handle a 404 page using React-Router?
Feb 22 in Node-js by Ashutosh
• 20,830 points
61 views

1 answer to this question.

0 votes

Here's the best way to implement a 404 page using React Router:

1. Set Up React Router

First, ensure you have React Router installed in your project:

npm install react-router-dom

2. Create a 404 Component

Create a dedicated component for the 404 page. For example:

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;

3. Configure Routes in React Router

Use a Route with a path="*" to catch all undefined routes and render the 404 component. This should be placed at the end of your route configuration to ensure it only matches when no other routes do.

Here’s an example of how to set this up:

// src/App.js

import React from 'react';

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import Home from './components/Home';

import About from './components/About';

import NotFound from './components/NotFound';

const App = () => {

  return (

    <Router>

      <Routes>

        {/* Define your routes */}

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />


        {/* Catch-all route for 404 */}

        <Route path="*" element={<NotFound />} />

      </Routes>

    </Router>

  );

};

export default App;

answered Feb 23 by Kavya

Related Questions In Node-js

0 votes
1 answer

What is the best way to trigger change or input event in react js?

To handle change or input events in ...READ MORE

answered Feb 22 in Node-js by Kavya
48 views
0 votes
0 answers

What is the best way to update and combine state using React's useState hook?

Can you explain What is the best ...READ MORE

14 hours ago in Node-js by Ashutosh
• 20,830 points
15 views
0 votes
1 answer

What is the best way to run npm install for nested folders?

Hello @kartik, If you want to run a ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,840 points
14,841 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to set read concern in MongoDB?

In MongoDB, you can set read concern ...READ MORE

answered Feb 23 in Node-js by Kavya
59 views
0 votes
1 answer

What is the best way to handle e and props in React TypeScript?

In React with TypeScript, handling events and ...READ MORE

answered Feb 23 in Node-js by Kavya
83 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP