React Lesson 14: React Router

⚛️ React CourseLesson 14 of 15 · 93% complete

React Router adds navigation and multiple pages to React apps. Without it, your app is a single page. With it, you have full multi-page navigation.

Installation

# Install React Router
npm install react-router-dom

Basic Setup

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

function App() {
  return (
    <BrowserRouter>
      {/* Navigation */}
      <nav>
        <NavLink to="/">Home</NavLink>
        <NavLink to="/about">About</NavLink>
        <NavLink to="/courses">Courses</NavLink>
      </nav>
      
      {/* Routes */}
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/about" element={<AboutPage />} />
        <Route path="/courses" element={<CoursesPage />} />
        <Route path="/courses/:id" element={<CourseDetailPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Dynamic Routes and useParams

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

function CourseDetail() {
  const { id } = useParams();  // get :id from URL
  const navigate = useNavigate();
  
  return (
    <div>
      <h1>Course #{id}</h1>
      <button onClick={() => navigate("/courses")}>Back to Courses</button>
      <button onClick={() => navigate(-1)}>Go Back</button>
    </div>
  );
}

🏋️ Practice Task

Build a mini website with 3 pages: Home (with intro text), Courses (with 3 course links), and CourseDetail (shows course name from URL params). Add navigation that highlights the active link.

💡 Hint: Install react-router-dom. Wrap in BrowserRouter. Use NavLink with className={({isActive}) => isActive ? “active” : “”} for active styling.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *