← Back to Chapters

BrowserRouter, Routes & Route

? BrowserRouter, Routes & Route

? Conceptual Overview

React Router enables Single Page Application (SPA) navigation. Instead of reloading the page, it updates the URL and swaps components dynamically.

The classic routing setup (before createBrowserRouter) relies on three core components: BrowserRouter, Routes, and Route.

? Mental Model

  • BrowserRouter → listens to URL changes
  • Routes → checks which route matches the URL
  • Route → renders the matching component

? BrowserRouter

BrowserRouter uses the browser’s History API (pushState, popstate) to change URLs without refreshing.

? App Entry Setup
// Root-level router wrapper
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

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

?️ Routes & Route

In React Router v6, Routes replaces Switch. Only the best matching route is rendered.

? Basic Routes
// Each Route maps a path to a JSX element
import { Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";

function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
);
}

export default App;

? Nested Routes

Nested routes allow layouts like dashboards where child pages render inside a parent UI.

? Nested Routing Example
// Nested routes render inside parent outlet
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>

? Dynamic Route Params

Route parameters allow URLs like /users/42.

? Dynamic Route
// :id captures dynamic values from URL
<Route path="/users/:id" element={<UserDetails />} />

? 404 Not Found Route

A wildcard * path catches unmatched URLs.

? 404 Route
// Catch-all route for unknown paths
<Route path="*" element={<NotFound />} />

? Navigation with Link

Link prevents page reloads and keeps SPA behavior intact.

? Navbar Example
// Client-side navigation
import { Link } from "react-router-dom";

function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}

? Best Practices

  • Always use BrowserRouter once at the root
  • Prefer Link over <a>
  • Use wildcard routes for 404 handling
  • Use nested routes for layouts

? Practice Tasks

  1. Add a /blog/:slug route
  2. Create nested dashboard routes
  3. Implement a 404 page