React Router and Multiple Pages
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.
Table of contents
What You Will Master Today
BrowserRouter to enable routing across the entire appRoutes & Route components* pathWhat 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.
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:
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.
The 4 Core Components Explained
React Router is built on four fundamental components. Understanding their roles is key to building any navigation system.
The History Wrapper
Wraps your entire application and connects it to the browser's URL bar. It uses the HTML5 History API (pushState, replaceState) to keep your UI in sync with the URL. Without this component at the very root of your app, no routing will work.
The Matching Engine
A container that looks through all its Route children and renders the first one whose path matches the current URL. In v6, Routes replaces the old Switch component and brings intelligent ranking of routes (it chooses the most specific match automatically).
The URL-Component Map
Defines a single mapping between a URL path and a React component. The path prop specifies the URL pattern, and the element prop receives the JSX that should render when the path matches. The special path "*" acts as a catch-all for any undefined routes.
The Navigation Anchor
Replaces the standard tag. When clicked, it updates the browser URL and triggers a component swap without reloading the page. This preserves all React state, scroll position, and provides a seamless user experience. For styling active links, use NavLink which adds an active class automatically.
Webbo3 Student Portal — Complete Code
Below is a fully functional React Router setup. The navigation links use Link, the route definitions use Routes and Route, and the wildcard path="*" catches any mistyped URL to show a custom 404 page.
// Import everything from react-router-dom import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; function Home() { return; } function Curriculum() { returnWebbo3 — JS Mastery
30‑Day Curriculum; } function About() { returnAbout Webbo3; } function NotFound() { return404 Page Not Found
; } function App() { return (); } } /> } /> } /> } />
🔬 Live demo: Click the links below to see how React Router swaps content without reloading the page.
Webbo3 — JavaScript Mastery
Welcome to Cohort 01. Build Real Projects with JavaScript + AI.
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.
| Feature | Traditional (Server-Side) | React Router (Client-Side) |
|---|---|---|
| Page reload on navigate | Full browser reload | Zero reload — instant transition |
| Perceived speed | Slow (network latency + server render) | Near-instant (JavaScript swaps DOM) |
| App state preserved | Lost on navigation (unless stored manually) | State stays alive in memory |
| Who handles routing | Server sends new HTML file | Browser JavaScript (History API) |
| SEO friendliness | Excellent (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.
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.
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={.
✗ Navigation works but URL doesn't update / page flashes
You used a standard tag instead of . Standard anchor tags always trigger a full browser navigation to a new document. Replace all navigation anchors with Link to enable client-side routing.
✗ 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 .
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).
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.
Challenges — Solidify Your Knowledge
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.
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.
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.
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.
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.
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