Course Lessons

JAVASCRIPT FOUNDATIONS + AI MINDSET

Back to Course

React Router and Multiple Pages

JAVASCRIPT... Lesson 26 of 41 11 min
Day 26 — React Router & Multiple Pages | Webbo3
DAY 26 · WEBBO3 COHORT 01

React Router
& Multiple Pages

Turn your single-page React app into a full multi-page experience — without a single browser reload. Learn how to map URLs to components, manage navigation, and protect routes with authentication.

React Router DOM BrowserRouter Client-Side Routing 404 Pages Protected Routes
01 / LEARNING OBJECTIVES

What You Will Master Today

Install and set up React Router DOM in a new or existing project
Use BrowserRouter to enable routing across the entire app
Create multiple pages with Routes & Route components
Navigate using Link instead of to prevent full reloads
Understand client-side routing vs server-side routing and why it matters
Build a custom 404 Not Found page using the wildcard * path
Implement protected / authenticated routes for secure pages
Use AI prompts to generate boilerplate and enhance routing structure
02 / CONCEPT

What is React Router?

By default, a React app is a single-page application (SPA). It loads one HTML document and then dynamically updates content using JavaScript. Without a routing library, you cannot bookmark a specific view, share a link to a user profile, or use the browser back/forward buttons to navigate between sections — the URL never changes. React Router is the de facto standard library that solves this. It synchronizes the browser URL with the React component tree. It watches the URL and conditionally renders the correct component, giving your app the feeling of multiple pages while technically remaining a single, fast-loading HTML document.

🏢 Think of it like a huge corporate headquarters. The URL is the room number. /lobby is the reception area, /finance is the accounting department. React Router is the internal digital directory board that instantly tells you "Finance is on Floor 3, Room 302" — guests don't walk outside and rebuild the building just to switch floors. They move internally, instantly.

💡

React Router is used by millions of production applications — from startup dashboards to enterprise portals like Netflix and Airbnb. It is one of the most downloaded npm packages in the entire JavaScript ecosystem, essential knowledge for any React developer.

03 / SETUP

Installing React Router

Open your terminal inside your React project directory (created with Vite or Create React App). Run the following command to install the latest version of React Router DOM:

# Using npm
npm install react-router-dom

# Or using yarn
yarn add react-router-dom

This installs the react-router-dom package — the web-specific binding for React Router. It includes every component you need: BrowserRouter, Routes, Route, Link, NavLink, and more. There is also a react-router core package, but for web development you always want react-router-dom.

⚠️ Version check: Ensure you install version 6 or higher. React Router v6 introduced a completely new API with Routes instead of Switch, and element prop instead of component. This entire lesson uses v6+ syntax, which is the modern standard.

06 / DEEP DIVE

Client-Side Routing Explained in Detail

Traditional websites (server-side routing) send a request to the server for every single page navigation. The server processes the request, builds an entire HTML document, and sends it back. This causes a visible white flash and loses all client-side state (like form inputs or scroll position). React Router implements client-side routing: after the initial page load, JavaScript intercepts navigation clicks, updates the browser URL, and dynamically swaps the React component tree — all without a single network request to fetch a new HTML page.

FeatureTraditional (Server-Side)React Router (Client-Side)
Page reload on navigateFull browser reloadZero reload — instant transition
Perceived speedSlow (network latency + server render)Near-instant (JavaScript swaps DOM)
App state preservedLost on navigation (unless stored manually)State stays alive in memory
Who handles routingServer sends new HTML fileBrowser JavaScript (History API)
SEO friendlinessExcellent (server sends full HTML)Needs configuration (SSR/SSG for crawlers)

🔬 Under the hood: When you click a Link, React Router calls history.pushState() — a browser API that adds a new entry to the browser's history stack and updates the URL without triggering a page load. The BrowserRouter component listens to these history changes via the popstate event and re-renders the matching Route. This is exactly how single-page apps feel like native mobile apps.

07 / DEBUGGING

Common Errors & Detailed Fixes

✗ useRoutes() may be used only in the context of a Router

You are trying to use Routes, Route, or Link outside of a router context. This usually happens when you forget to wrap your entire component with . Check your main.jsx or index.js file.

// Correct setup in main.jsx
root.render();

✗ Using component= instead of element=

React Router v6 completely replaced the component prop with element. If you write it will fail silently or throw an error. You must pass JSX: element={}.

} />

✗ Routes are not rendering anything / blank page

Make sure your routes are wrapped inside a component, not just placed directly inside . In v6, every must be a child of .

08 / ADVANCED CONCEPT

Protected Routes — Guarding Sensitive Pages

In real applications, not every page should be accessible to everyone. A Dashboard, User Profile, or Admin Settings page must only be visible to authenticated users. React Router doesn't have a built-in auth system, but it provides the primitives to build one. A Protected Route is a wrapper component that checks an authentication condition. If the user is not logged in, it either renders a fallback (like "Please log in") or redirects them to the login page.

The pattern below demonstrates a simple protected route. The isLoggedIn prop simulates authentication state (in production this would come from React Context, Redux, or a custom hook).

// ProtectedRoute wrapper component function ProtectedRoute({ isLoggedIn, children }) { if (!isLoggedIn) return

Please log in to access this page

; return children; } // Usage inside Routes — Dashboard is now guarded } />

🚀 Production upgrade: Instead of showing a static message, use the useNavigate() hook inside the ProtectedRoute to redirect to /login when unauthenticated. Pass the intended destination in the URL so you can redirect back after login. The real auth state should come from a global context or state management library, not hardcoded props.

09 / PRACTICE

Challenges — Solidify Your Knowledge

BEGINNER

1. Add a Contact Page

Create a /contact route with a simple page. Add a corresponding Link in the navigation bar and ensure the route appears in the block.

BEGINNER

2. Style the Navbar with Active Links

Replace Link with NavLink. Use its className callback or style prop to apply distinct styling (e.g., bold text, underline, color change) to the link that matches the current URL.

BEGINNER

3. Add a Persistent Footer

Place a footer component inside BrowserRouter but outside the block. This way it appears on every single page (Home, About, Dashboard) without needing to duplicate it inside each page component.

INTERMEDIATE

4. Build Login + Protected Dashboard

Create a simple Login page with a button that toggles an isLoggedIn state. Pass that state to a ProtectedRoute component. The Dashboard should only be visible after "logging in". Use useNavigate to redirect to login when unauthenticated.

10 / INTERVIEW PREP

Interview Questions & Model Answers

Q: What is React Router and why is it necessary?

A library that enables client-side routing in React SPAs. It maps URL paths to specific components, allowing users to navigate between views, bookmark pages, and use browser history — all without full page reloads.

Q: Difference between BrowserRouter and HashRouter?

BrowserRouter uses clean, standard URLs (/about) and relies on the History API. HashRouter stores the path after a # symbol (/#/about) and works even without server-side configuration. BrowserRouter is the modern standard.

Q: Why use Link instead of an anchor tag?

Link prevents the default full-page reload. It communicates with the router to update the URL and re-render only the necessary components, preserving React state, context, and delivering a seamless app-like experience.

Q: How do you handle 404 pages in React Router?

By adding a } /> as the last route inside . The asterisk acts as a wildcard that matches any URL not defined above it, displaying a custom 404 component.

🤖
AI LEARNING PROMPTS
"Create a React Router navbar with Tailwind CSS that highlights the active page"
"Generate a React Router 404 page with a funny animation"
"Create a protected route system in React Router v6 that redirects to /login"
📓 Learning Journal — Day 26

Today I learned how to turn a single-page React app into a full multi-page experience using React Router. I now understand that BrowserRouter is the foundation that connects to the browser's history, Routes is the container that holds all path definitions, Route is the connector that maps a URL to a component, and Link is how users move between pages without a single browser reload. Client-side routing means JavaScript handles navigation instead of the server, which makes apps feel instant and preserves state. I also know how to build a 404 catch-all page using path="*" as the last route, and how to create protected routes that check authentication before rendering sensitive components. Next I'll tackle dynamic routes with useParams and nested layouts with Outlet. 🚀

WEBBO3 COHORT 01 · DAY 26 · REACT ROUTER & MULTIPLE PAGES

AI-Assisted JavaScript Learning · Build Real Projects

Complete this lesson

Mark as complete to track your progress