Monday, 3 February 2025

How to handle Undefined Routes in React Router?

We can use wildcard route to match any path that is not explicitly defined.


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


Above snippet catch all routes for undefined URLs.

 

Follow below step-by-step procedure to build the complete working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘handle-undefined-routes’.

 

Project structure looks like below.

 

Step 2: Navigate to the project directory and install react router dom by executing below commands.

cd handle-undefined-routes
npm install react-router-dom

Step 3: Create pages folder in src folder and define Home and Help pages.

 

HomePage.jsx

export default function HomePage() {
  return (
    <>
      <h1>Home Page</h1>
    </>
  );
}

HelpPage.jsx

export default function HelpPage() {
  return (
    <>
      <h1>Help Page</h1>
    </>
  );
}

Step 4: Update App.jsx with below content.

 

App.jsx

import { BrowserRouter, Routes, Route } from "react-router-dom";
import HomePage from "./pages/HomePage";
import HelpPage from "./pages/HelpPage";
import NotFound from "./pages/NotFound";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />}></Route>
        <Route path="/help" element={<HelpPage />}></Route>

        {/* Catch-all route for undefined URLs */}
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Step 5: Update main.jsx with below content.

 

main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Step 6: Build and run the application by executing below commands.

  cd handle-undefined-routes
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see home page screen.



Open the url ‘http://localhost:5173/help’, you will see Help Page screen.

 


Open the url ‘http://localhost:5173/abcde’, you will see page not found error.

 


You can download the application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment