R

React Handbook

Clean • Professional

React Router

4 minute

React Router

Modern web apps often need multiple pages — like Home, About, and Contact — but React applications are Single Page Applications (SPAs). That means the entire app runs on one HTML file (index.html), and React dynamically updates the view without reloading the page.

To handle page navigation efficiently, we use React Router — the standard routing library for React.

What is React Router?

React Router is a library that lets you create and manage navigation and routes in React applications.

It enables you to:

  • Display different components based on the URL.
  • Navigate between pages without reloading.
  • Handle nested, dynamic, and protected routes.

React Router DOM is the version designed for web apps.

npm install react-router-dom

BrowserRouter – The Root Wrapper

  • BrowserRouter is the main router provider.
  • It keeps the UI in sync with the URL using the browser’s History API.
  • All your routes should be wrapped inside <BrowserRouter>.

Example:

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";

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

export default App;
  • <BrowserRouter> wraps your entire application.
  • <Routes> is a container for multiple route definitions.
  • Each <Route> maps a path to a component.

Route – Defining Paths & Components

A Route defines which component should be rendered for a specific path.

Example:

<Route path="/contact" element={<Contact />} />
  • path defines the URL.
  • element defines the React component to display.

You can define as many routes as you need.

Routes – Organizing All Routes Together

<Routes> is a parent component that holds all your <Route> definitions.

It ensures only one route matches and renders at a time (exclusive matching).

Example:

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route path="/contact" element={<Contact />} />
</Routes>

Nested Routes – Building Hierarchical Pages

React Router allows you to create nested routes — great for dashboards or layouts that share common UI (like a sidebar or navbar).

Example:

import { BrowserRouter, Routes, Route, Outlet, Link } from "react-router-dom";

function DashboardLayout() {
  return (
    <div>
      <h2>Dashboard</h2>
      <nav>
        <Link to="profile">Profile</Link> |{" "}
        <Link to="settings">Settings</Link>
      </nav>
      <Outlet /> {/* Renders nested routes here */}
    </div>
  );
}

function Profile() {
  return <h3>Profile Page</h3>;
}

function Settings() {
  return <h3>Settings Page</h3>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<DashboardLayout />}>
          <Route path="profile" element={<Profile />} />
          <Route path="settings" element={<Settings />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;
  • <Outlet> is a placeholder for nested routes.
  • Nested URLs like /dashboard/profile and /dashboard/settings are automatically handled.
  • You can nest multiple levels deep.

Redirects – Navigating Automatically

Sometimes you need to redirect users automatically — for example, from / to /home or after form submission.

React Router v6 uses <Navigate> for redirects.

Example:

import { Navigate } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Navigate to="/home" />} />
        <Route path="/home" element={<h2>Home Page</h2>} />
      </Routes>
    </BrowserRouter>
  );
}

Navigation – Using Link & useNavigate

Link Component

Instead of using <a> tags (which reload the page), React Router provides <Link> for smooth client-side navigation.

import { Link } from "react-router-dom";

<Link to="/about">Go to About</Link>

useNavigate Hook

useNavigate() is a powerful hook for programmatic navigation — for example, redirecting users after login.

import { useNavigate } from "react-router-dom";

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

  function handleLogin() {
    // logic for authentication
    navigate("/dashboard");
  }

  return <button onClick={handleLogin}>Login</button>;
}

Handling 404 (Not Found) Routes

To display a fallback page when no routes match, add a “*” route.

<Route path="*" element={<h2>404 - Page Not Found</h2>} />

React Router Hooks Overview

HookDescription
useNavigate()Navigate programmatically
useParams()Access dynamic route parameters
useLocation()Access current URL details
useSearchParams()Manage query parameters

Example (Dynamic Params):

<Route path="/user/:id" element={<User />} />

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

Example – Complete React Router App

import React from "react";
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  useNavigate,
  Navigate,
} from "react-router-dom";

function Home() {
  return <h2>Welcome to Home Page</h2>;
}

function About() {
  return <h2>About Us</h2>;
}

function Contact() {
  return <h2>Contact Page</h2>;
}

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link> |{" "}
        <Link to="/about">About</Link> |{" "}
        <Link to="/contact">Contact</Link>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="*" element={<h2>404 Not Found</h2>} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Why Use React Router?

React Router makes your web apps:

  • Fast – Client-side navigation without reloads
  • Dynamic – Load components based on URL
  • Modular – Easy to manage pages and layouts
  • SEO-Friendly – Especially when used with frameworks like Next.js or SSR setups

Summary Table

ConceptDescription
BrowserRouterWraps the app and enables routing
Routes & RouteDefine URL paths and corresponding components
Nested RoutesBuild layouts and child pages
NavigateRedirect users programmatically
Link & useNavigateHandle navigation without page reload
useParams, useLocationAccess dynamic or current route data


Article 0 of 0