React Router
Turn your single-page app into a multi-page experience with client-side routing.
What you will learn
- Install and set up React Router
- Define routes for different pages
- Link between pages without reloads
Multiple pages, no reloads
React apps are single-page apps (often shortened to SPA) — meaning the browser loads one HTML page once, and JavaScript swaps the content in and out as you move around, instead of fetching a fresh page from the server each time.
But a real site still needs different pages — a Home page, an About page, and so on. React Router gives us client-side routing (“client-side” means it happens right in the browser, with no server round-trip): it shows different components for different URLs, so it feels like separate pages even though no full reload ever happens.
npm install react-router-domReact Router is a separate package, so first you install it into your project with this one terminal command. After it finishes, you can import its pieces (BrowserRouter, Routes, Route, Link) in your code.
// App.jsx
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import Home from "./Home.jsx";
import About from "./About.jsx";
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}Here is how the four pieces work together to fake multiple pages:
<BrowserRouter>wraps the whole app and watches the URL in the address bar.<Link to="/about">is a clickable navigation item. Unlike a normal<a>link, it changes the URL without reloading the page.<Routes>is the switchboard: it looks at the current URL and shows only the one matching route.<Route path="/about" element={<About />} />says “when the URL is/about, render theAboutcomponent”. Thepath="/"route rendersHome.
So clicking About changes the URL to /about, <Routes> notices, and swaps Home out for About — instantly, with no full page reload. It looks and feels like separate pages, but it is all one fast single-page app.
Tip: Use <Link to="/about"> instead of <a href> for internal navigation — it switches pages instantly without reloading the whole app.
Note: This lesson’s code runs in a real Vite project (it needs the installed router package), so the examples are shown as code rather than live previews.
Q. Which component do you use for internal navigation in React Router?
✍️ Practice
- Set up a router with Home and About pages and links between them.
- Add a third page (Contact) with its own route.
🏠 Homework
- Build a 3-page site (Home, Courses, Contact) using React Router.