Skip to main content
React Introduction
CHAPTER 17 Beginner

React Router Basics

Updated: May 13, 2026
20 min read

# React Router Basics

1. Introduction

React is a library for building Single Page Applications (SPAs). This means the browser only ever loads one index.html file. So, how do we create an application with a "Home" page, an "About" page, and a "Contact" page with different URLs (/about, /contact)? We use Client-Side Routing. The industry-standard library for this is react-router-dom.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand client-side routing vs. traditional server routing.
  • Install and configure react-router-dom.
  • Set up routes to display different components based on the URL.
  • Use the <Link> component to navigate without refreshing the page.

3. Beginner-Friendly Explanations

How Routing Works in an SPA

In a traditional website, clicking an anchor tag <a href="/about"> tells the browser to make a full request to the server, download a new HTML file, and completely refresh the page. In React Router, we stop that from happening. When the URL changes, React Router intercepts the request, looks at its configuration, unmounts the current component (e.g., <HomePage>), and mounts the new component (e.g., <AboutPage>) instantly—no refresh required!

4. Syntax Explanation

Step 1: Installation

Because routing is not built into React core, you must install the package via your terminal.
bash
1
npm install react-router-dom

Step 2: Setting up the Router

You wrap your entire application inside a <BrowserRouter> component. Then, you use <Routes> and <Route> to define the paths.

```jsx id="ch17_ex1" // App.jsx import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; import NotFound from './NotFound';

function App() { return ( <BrowserRouter> {/* Everything inside Routes changes based on the URL */} <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> {/* The * path acts as a catch-all for 404 pages */} <Route path="*" element={<NotFound />} /> </Routes> </BrowserRouter> ); } export default App;

123
### Step 3: Navigation with `<Link>`
**NEVER** use standard `<a href="...">` tags for internal links in React Router. It will trigger a full page reload, wiping out your React State! Instead, use the `<Link>` component provided by the library.

jsx id="ch17_ex2" // Example React component import { Link } from 'react-router-dom';

function Navbar() { return ( <nav> {/* Correct SPA Navigation */} <Link to="/">Home</Link> <Link to="/about">About Us</Link> {/* ❌ WRONG: Do not do this for internal routing! */} {/* <a href="/about">About Us</a> */} </nav> ); }

12345678910111213141516171819202122232425
## 5. Output Explanations
When the user clicks the `<Link to="/about">`, the browser URL changes to `yourapp.com/about`. The `<Routes>` component detects this change, searches its list, finds the matching `<Route path="/about">`, and renders the `<About />` component inside the page instantly.

## 6. Real-World Examples
Any complex web app uses this:
- Gmail: `mail.google.com/mail/u/0/#inbox` vs `.../#sent`
- Twitter: `twitter.com/home` vs `twitter.com/notifications`
They feel instant because they are SPAs using client-side routing!

## 7. Common Mistakes
- **Using `<a>` tags:** As mentioned, this causes a full page reload. Only use `<a>` tags for external links (e.g., `<a href="https://google.com">`).
- **Forgetting the `<BrowserRouter>`:** If you try to use `<Link>` outside of a `<BrowserRouter>` wrapper, React will throw a massive error.

## 8. Best Practices
- Keep your routes organized in your main `App.jsx` or a dedicated `Router.jsx` file so other developers can easily see the architecture of your app at a glance.
- Always include a `path="*"` catch-all route to display a friendly 404 Not Found page if the user types an invalid URL.

## 9. Exercises
1. Install `react-router-dom` in a practice project.
2. Create three components: `Home`, `Dashboard`, and `Settings`.
3. Set up routes so that `/` goes to Home, `/dashboard` goes to Dashboard, and `/settings` goes to Settings.

## 10. Mini Project: Multi-Page React App
Let's build a functional navigation shell with a shared layout.

jsx id="ch17_proj1" // Example React component import React from 'react'; import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

// --- PAGE COMPONENTS --- const HomePage = () => <div className="p-8 text-2xl font-bold">🏠 Welcome Home</div>; const ServicesPage = () => <div className="p-8 text-2xl font-bold">🚀 Our Services</div>; const ContactPage = () => <div className="p-8 text-2xl font-bold">✉️ Contact Us</div>; const ErrorPage = () => <div className="p-8 text-2xl font-bold text-red-500">404 - Page Not Found</div>;

// --- LAYOUT COMPONENT --- const Navigation = () => ( <nav className="bg-slate-800 text-white p-4 flex gap-6 shadow-md"> <Link to="/" className="hover:text-blue-400 font-medium transition">Home</Link> <Link to="/services" className="hover:text-blue-400 font-medium transition">Services</Link> <Link to="/contact" className="hover:text-blue-400 font-medium transition">Contact</Link> </nav> );

// --- MAIN APP --- export default function App() { return ( <BrowserRouter> <div className="min-h-screen bg-slate-50 font-sans text-slate-800"> {/* Navigation sits OUTSIDE the Routes, so it is visible on EVERY page! */} <Navigation /> <main className="max-w-4xl mx-auto mt-8 bg-white rounded-xl shadow-sm border border-slate-200 min-h-[400px]"> <Routes> <Route path="/" element={<HomePage />} /> <Route path="/services" element={<ServicesPage />} /> <Route path="/contact" element={<ContactPage />} /> <Route path="*" element={<ErrorPage />} /> </Routes> </main> </div> </BrowserRouter> ); } ``

11. Coding Challenges

Challenge 1: Modify the
<Navigation> component to use the <NavLink> component from react-router-dom. Read the docs to learn how <NavLink> allows you to apply an "active" class to the link when the user is on that specific page.

12. MCQs with Answers

Q1: Why do we use
<Link to="..."> instead of <a href="..."> in React Router? A) <Link> is faster to type. B) <Link> prevents the browser from doing a full page refresh, preserving React State. C) <a> tags are deprecated in HTML5. *Answer: B*

Q2: Which component acts as the foundational wrapper required for React Router to work? A) <Routes> B) <AppRouter> C) <BrowserRouter> D) <RouterWrap> *Answer: C*

13. Interview Questions

  • Q: Explain what a Single Page Application (SPA) is and how client-side routing differs from server-side routing.
  • Q: How do you handle 404 (Not Found) errors in React Router? *(Answer: Using the wildcard route path="*")*

14. FAQs

Can I have routes inside of routes? Yes! This is called "Nested Routing". You could have a
/dashboard route, and inside the Dashboard component, define sub-routes like /dashboard/analytics and /dashboard/settings.

15. Summary

React Router is essential for building complete applications. By wrapping your app in a
<BrowserRouter>, defining URL paths with <Route>, and navigating via <Link>, you can create complex, multi-page experiences that load instantly.

16. Next Chapter Recommendation

Hardcoding exact paths like
/about is great, but what if you have an e-commerce store with 10,000 products? You can't write 10,000 <Route>` tags! In Chapter 18: Dynamic Routing in React, we will learn how to use URL parameters to generate dynamic pages.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·