React Router Basics
# React Router Basics
1. Introduction
React is a library for building Single Page Applications (SPAs). This means the browser only ever loads oneindex.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.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;
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> ); }
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.