Mastering React Router DOM: The Shortcut to Smooth Navigation in React 🚀

Abhishek RautAbhishek Raut
3 min read

If your app's navigation feels like a never-ending road trip without GPS, it's time to bring in React Router DOM. It’s the magic wand 🪄 that makes navigating through your app as smooth as swiping through Instagram stories. Let’s explore how to set it up, add error handling, and sprinkle some React goodness.


Why Do You Need React Router DOM?

Imagine building a food delivery app (yes, like Swiggy 🍔). You want users to seamlessly navigate between the Home, Menu, and Checkout pages without reloading the entire app. That’s where React Router DOM swoops in like a superhero 🦸‍♂️, saving you from a spaghetti-code disaster.


Step-by-Step Guide

Here’s how you can set up routing for your app like a pro, with just the right touch of fun.


1. Install React Router DOM

First, you need to install it. Think of this as adding a GPS to your app:

npm install react-router-dom

2. Define Your Routes

Use createBrowserRouter to map URLs to your components. Think of this as setting up the "playlist" of your app—where each route is a song. 🎵

import React from "react";
import ReactDOM from "react-dom/client";
import {
  createBrowserRouter,
  RouterProvider,
  Outlet,
  Link,
  useRouteError
} from "react-router-dom";

// Layout Component
const AppLayout = () => (
  <div>
    <h1>React Router DOM: Navigation Made Easy ✨</h1>
    <nav>
      <Link to="/">🏠 Home</Link> | <Link to="/about">ℹ️ About</Link> | <Link to="/contact">📞 Contact</Link>
    </nav>
    <hr />
    <Outlet /> {/* This is where child routes will render */}
  </div>
);

// Pages
const Home = () => <h2>Welcome to the Home Page 🏡</h2>;
const About = () => <h2>About Us: We make routing fun! 🎉</h2>;
const Contact = () => <h2>Contact Us: Let’s connect 📞</h2>;

// Error Component
const ErrorPage = () => {
  const error = useRouteError();
  return (
    <div>
      <h2>Oops! Something went wrong 🙈</h2>
      <p>{error.statusText || error.message}</p>
    </div>
  );
};

// Create Browser Router
const router = createBrowserRouter([
  {
    path: "/",
    element: <AppLayout />,
    errorElement: <ErrorPage />, // Handles all unmatched routes
    children: [
      { path: "/", element: <Home /> },
      { path: "/about", element: <About /> },
      { path: "/contact", element: <Contact /> },
    ],
  },
]);

3. Render the Router

Wrap your app in RouterProvider. Think of it as plugging in the GPS and turning it on. 🔌

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<RouterProvider router={router} />);

How Error Handling Works

Using useRouteError, we gracefully handle 404 or other route issues. Imagine this like a polite waiter saying, "Sir/Madam, this route doesn’t exist. Please check the menu again. 🧾"

const ErrorPage = () => {
  const error = useRouteError();
  return (
    <div>
      <h2>Oops! We couldn’t find that page 😥</h2>
      <p>
        {error.status === 404
          ? "This route does not exist. Try another link!"
          : "Something unexpected happened."}
      </p>
    </div>
  );
};

Real-Life Analogy of Routing

Think of your app as a shopping mall 🏢:

  • Home Page: The entrance.

  • About Page: The "About Us" section near the reception.

  • Contact Page: A helpdesk for inquiries.

  • Error Page: The “No Entry” sign when you try to walk into a restricted area.

Routing ensures your users don’t get lost in the mall of your app. 🎯


Conclusion

React Router DOM isn’t just a tool; it’s your app’s GPS, ensuring smooth navigation and happy users. Whether you’re building a personal portfolio or the next Swiggy clone 🍕, mastering this library is a must-have skill.

Now go ahead, implement this, and let your app shine brighter than a Netflix series on autoplay! ✨

10
Subscribe to my newsletter

Read articles from Abhishek Raut directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abhishek Raut
Abhishek Raut

🔭 I’m currently working on Full Stack Project 👯 I’m looking to collaborate on Animated Websites 🌱 I’m currently learning Data Science 💬 Ask me about React GSAP ⚡ Fun fact I am Working on Project and learning tech stack used in That