React Router Tutorial: Build Nested and Dynamic Routes in React

Build one Course Explorer from two static pages into dynamic courses, nested lessons, active navigation, a simulated protected dashboard and useful fallbacks.

KnowledgeGate Team

Exam prep & CS education

Updated 2 Nov 20266 min read
React Router Tutorial: Build Nested and Dynamic Routes in React

A React app can swap components with a condition, but that alone does not make the open screen visible in the URL. The back button, bookmarks and direct links remain disconnected. React Router connects paths to UI, so /courses/react-101 can be copied and revisited without a document reload. The Course Explorer connects each route to its corresponding screen, including nested and dynamic paths.

1. What React Router changes in a single-page React app

With /courses/react-101 in the address bar, the router compares route patterns, chooses the matching branch, and React renders React Foundations. React still renders components; the router decides which branch belongs to the location, as the official React Router installation guide explains.

showCourses ? <Courses /> : <Home /> changes UI, but it does not create bookmarkable /courses and / locations. <Route path="courses" element={<CourseLayout />} /> does. The routing setup uses current Declarative Mode with BrowserRouter, Routes and Route, not framework loaders or server APIs. The React learning path sequences JSX, state, hooks, routing, forms and Redux. The Course Explorer focuses on route matching, nesting and navigation.

2. Install the router and make the first two routes

In an existing React app, run npm i react-router. Wrap the app once in src/main.jsx:

jsx
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router";
import App from "./App.jsx";

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

Start src/App.jsx with two routes:

jsx
import { Route, Routes } from "react-router";

function Home() { return <h2>Course Explorer Home</h2>; }
function Courses() { return <h2>Choose a course</h2>; }

export default function App() {
  return <main>
    <h1>KnowledgeGate Course Explorer</h1>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="courses" element={<Courses />} />
    </Routes>
  </main>;
}

At /, the H1 is followed by Course Explorer Home. At /courses, it stays and the second line becomes Choose a course. path="courses" resolves to /courses in the root context. Use the React and Redux Course for focused React practice.

React Router's navigation guide defines Link and NavLink as router-aware APIs; NavLink also exposes active state. Add NavLink to the import and place this above <Routes>:

jsx
function SiteNav() {
  return <nav>
    <NavLink to="/" end className={({ isActive }) => isActive ? "active" : ""}>Home</NavLink>{" "}
    <NavLink to="/courses" className={({ isActive }) => isActive ? "active" : ""}>Courses</NavLink>
  </nav>;
}

Render <SiteNav /> above <Routes> and add .active { font-weight: 700; color: #2563eb; }. At /, only Home is active. At /courses, Courses is active. At /courses/react-101, Courses remains active because its URL is a prefix, while end prevents Home from staying active. Keep Link for ordinary clicks; useNavigate fits the successful sign-in action because navigation follows a completed event.

4. Work a dynamic route with useParams and real values

Add Link and useParams to the import, then use exact course data:

jsx
const courses = {
  "react-101": { title: "React Foundations", level: "Beginner", lessons: [
    { id: "router-basics", title: "Router Basics", minutes: 18 },
    { id: "nested-routes", title: "Nested Routes", minutes: 24 },
  ]},
  "js-201": { title: "Modern JavaScript", level: "Intermediate", lessons: [
    { id: "closures", title: "Closures", minutes: 21 },
    { id: "promises", title: "Promises", minutes: 27 },
  ]},
};

CourseIndex returns <Link to="react-101">React Foundations</Link> and <Link to="js-201">Modern JavaScript</Link>. At /courses, the relative to="react-101" becomes /courses/react-101. React Router documents the colon field as a dynamic segment. Map it with <Route path=":courseId" element={<CourseDetail />} />:

jsx
function CourseDetail() {
  const { courseId } = useParams();
  const course = courses[courseId];
  if (!course) return <p>Course not found</p>;
  return <><h2>{course.title}</h2><p>Level: {course.level}</p>
    <p>{course.lessons.length} lessons</p></>;
}

For /courses/react-101, courseId === "react-101", so the result is React Foundations, Level: Beginner, 2 lessons. /courses/js-201 gives Modern JavaScript, Level: Intermediate, 2 lessons. /courses/css-999 has no matching object, so it displays Course not found.

5. Nest lesson routes and render them through Outlet

Add Outlet to the router import and refactor the branch. Child paths have no leading slash because they are relative to courses:

jsx
<Route path="courses" element={<CourseLayout />}>
  <Route index element={<CourseIndex />} />
  <Route path=":courseId" element={<CourseDetail />} />
  <Route path=":courseId/lessons/:lessonId" element={<LessonDetail />} />
</Route>

CourseLayout returns <section><h2>Course Library</h2><Outlet /></section>. The heading remains while the matched child fills Outlet. In the React course detail, <Link to="lessons/router-basics">Open Router Basics</Link> resolves relative to the current course.

LessonDetail reads both parameters, finds courses[courseId], then uses course?.lessons.find((item) => item.id === lessonId). If either lookup fails, it returns Lesson not found. Otherwise it renders {course.title}: {lesson.title} ({lesson.minutes} minutes).

At /courses/react-101/lessons/router-basics, the parameters are react-101 and router-basics; the output is React Foundations: Router Basics (18 minutes). At /courses/js-201/lessons/promises, they select Modern JavaScript: Promises (27 minutes).

Route tree showing /, /courses, nested course and lesson routes flowing into an Outlet.

6. Redirect after login, protect one route and catch unknown URLs

This is an in-memory simulation, not production authentication. Import useState from React and Navigate plus useNavigate from react-router. In App, set const [isLoggedIn, setIsLoggedIn] = useState(false);, then put these routes before the catch-all:

jsx
<Route path="login" element={<Login onLogin={() => setIsLoggedIn(true)} />} />
<Route path="dashboard" element={
  isLoggedIn ? <Dashboard /> : <Navigate to="/login" replace />
} />
<Route path="*" element={<NotFound />} />

Dashboard returns <h2>Welcome, student@example.com</h2>. NotFound shows Page not found and <Link to="/">Return home</Link>. In Login, create const navigate = useNavigate() and a form with an email input whose defaultValue is student@example.com. Its Sign in submit handler calls event.preventDefault(), onLogin(), then navigate("/dashboard", { replace: true }).

Opening /dashboard while logged out replaces it with /login. Submitting changes state to true, replaces Login with /dashboard, and shows Welcome, student@example.com. /anything-else matches *. Refreshing resets the demo state.

Authentication flow from /login to /dashboard, with unknown paths showing Page not found.

7. Diagnose six common React Router mistakes

  1. Hooks fail outside router context: wrap App once in BrowserRouter.

  2. A link displays /courses/:courseId: use the concrete /courses/react-101; keep :courseId only in a route pattern.

  3. The child URL changes but no child appears: render Outlet in CourseLayout.

  4. An internal click reloads the document: replace <a href="/courses"> with <Link to="/courses">.

  5. Unknown paths show a blank area: add the * route after specific routes.

  6. A direct refresh gives a host 404: configure the host's documented SPA fallback. <Routes> cannot repair a server response.

Debug by copying the failing URL, checking the console, confirming BrowserRouter, comparing the concrete URL with route patterns, inspecting useParams(), checking parent layouts for Outlet, then testing a fresh load separately from a client-side click.

8. Prove the router works, then choose the next step

  1. Predict /courses/js-201/lessons/closures: courseId = "js-201", lessonId = "closures", so the exact line is Modern JavaScript: Closures (21 minutes).

  2. Add { id: "route-errors", title: "Route Errors", minutes: 16 } to react-101. /courses/react-101/lessons/route-errors must show React Foundations: Route Errors (16 minutes). The React lesson count changes from 2 to 3; JavaScript stays at 2.

  3. At /courses/react-101, Courses is active and Home is not because Home uses end. Visit /missing-page, confirm Page not found, select Return home, and confirm Home becomes active.

Also explain why Link fits ordinary internal clicks while useNavigate fits a successful form submission, and why a nested route can match yet display nothing without Outlet.

  • BrowserRouter supplies routing context.

  • Routes selects a branch, and Route maps patterns to elements.

  • NavLink exposes active state.

  • useParams turns react-101 and router-basics into the 18-minute result.

  • Outlet places the nested screen.

  • Navigate and * handle redirects and unknown paths.

Rebuild the route tree from the diagram without copying, then pass all three exercises. Continue with the React and Redux course for focused React learning, choose the MERN Stack Course when moving towards a full-stack project, or browse Coding & Skills for another topic.