React Router
Client-side routing for single-page apps - matching URLs to components, navigation, route params, and nested layouts.
What it is, in plain English: React itself has no built-in concept of pages or URLs -- it's just a UI library. React Router is the standard library that maps URL paths to components, so a React app can have multiple 'pages' that change the URL without a full page reload. It handles navigation, dynamic route parameters (like /users/:id), nested layouts, and reading/writing the browser's URL and history.
Giving a React app multiple "pages"
React itself only knows how to render components -- it has no idea what a URL is. React Router fills that gap: it watches the browser's URL and renders the matching component, all without a full page reload (which is what makes it a Single Page App).
Basic setup
// npm install react-router-dom
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
// Visiting /about renders <About />. Visiting /contact renders <Contact />.
// No full page reload happens -- React swaps components instantly.Navigation with Link (not <a>)
import { Link } from "react-router-dom";
function Nav() {
return (
<nav>
{/* ✗ <a href="/about"> would cause a FULL page reload */}
{/* ✓ <Link> intercepts the click and updates the URL without reloading: */}
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}Dynamic route parameters
// :id is a placeholder -- matches anything in that position:
<Route path="/products/:id" element={<ProductDetail />} />
// Inside ProductDetail, read the matched value with useParams:
import { useParams } from "react-router-dom";
function ProductDetail() {
const { id } = useParams(); // "/products/42" → id = "42"
return <h1>Viewing product {id}</h1>;
}Programmatic navigation
import { useNavigate } from "react-router-dom";
function LoginForm() {
const navigate = useNavigate();
function handleSubmit(e) {
e.preventDefault();
// ... log the user in ...
navigate("/dashboard"); // redirect after successful login
}
return <form onSubmit={handleSubmit}>...</form>;
}
Try It Yourself (JSX)
Official Sources
The Codex links only to official documentation. No third-party tutorials.