← Back to Chapters

React Router

? React Router

? Quick Overview

React Router is the official routing solution for React applications. It enables navigation between pages without reloading the browser, preserving the single-page application (SPA) experience.

Version 6.6+ adds powerful features like data loading, simplified routing configuration, and built-in error handling.

? Key Concepts

  • Client-side routing
  • Route configuration objects
  • Nested routes with layouts
  • URL parameters
  • Error boundaries

? Installation

? View Code Example
// Install React Router DOM package
npm install react-router-dom

?️ Basic Router Setup

? View Code Example
// index.js - application entry with router configuration
import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import App from "./App";
import About from "./About";
import Contact from "./Contact";

const router = createBrowserRouter([
{ path: "/", element: <App /> },
{ path: "/about", element: <About /> },
{ path: "/contact", element: <Contact /> }
]);

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

The RouterProvider enables navigation by matching URLs with route definitions.

? Navigation

? View Code Example
// Navbar component using Link and useNavigate
import { Link, useNavigate } from "react-router-dom";

function Navbar() {
const navigate = useNavigate();

return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
<button onClick={() => navigate("/contact")}>Go to Contact</button>
</nav>
);
}

export default Navbar;

? Nested Routes

? View Code Example
// App.js layout with Outlet for nested routes
import { Outlet, Link } from "react-router-dom";

function App() {
return (
<div>
<h2>Welcome</h2>
<Link to="about">About</Link>
<Link to="contact">Contact</Link>
<Outlet />
</div>
);
}

export default App;

? URL Parameters

? View Code Example
// Reading dynamic URL parameter
import { useParams } from "react-router-dom";

function User() {
const { id } = useParams();
return <h4>User ID: {id}</h4>;
}

export default User;

? Error Handling

? View Code Example
// Defining errorElement for route failures
const router = createBrowserRouter([
{
path: "/",
element: <App />,
errorElement: <h3>Oops! Page not found.</h3>
}
]);

? Tips & Best Practices

  • Always define routes using createBrowserRouter
  • Organize routes in a dedicated file
  • Use Outlet for layouts
  • Provide a global error UI

? Try It Yourself

  1. Create Home, About, and Contact routes
  2. Add /user/:id route
  3. Implement nested routes
  4. Add a 404 error page