📖 Notes LESSON 22 OF 32

React Router

⏱️ 30 min
⚛️ React

Multiple Pages, One App

React apps are Single Page Applications — React Router swaps components in and out based on the URL without a full page reload.

Core Building Blocks

🌐
BrowserRouter
Wraps the whole app, enabling URL-based routing.
🗺️
Routes / Route
Maps a URL path to the component that should render there.
🔗
Link
Replaces <a> tags — navigates without a full page reload.
🧭
useNavigate / useParams
Navigate programmatically, or read dynamic segments from the URL.
Routing Setup
JSX
import { BrowserRouter, Routes, Route, Link, useNavigate, useParams } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/courses">Courses</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/courses" element={<Courses />} />
        <Route path="/courses/:id" element={<CourseDetail />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

function CourseDetail() {
  const { id } = useParams();        // read /courses/:id
  const navigate = useNavigate();
  return <button onClick={() => navigate(-1)}>Back</button>;
}
The catch-all route
path="*" matches any URL that didn't match an earlier Route — always put it last, and use it to render a 404 page.
🗒 Cheat Sheet 📝 Worksheet