React Router
React Router is the most popular library for adding pages and navigation to a React single-page app. It maps URLs to components and updates the page without a full reload. This chapter uses React Router v6.
Install React Router
npm install react-router-domadded 3 packages in 2s
Defining Routes
Use Link instead of <a> for internal links; it changes the URL without reloading the page. The * path catches anything that does not match.
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function Home() { return <h1>Home</h1>; }
function About() { return <h1>About me</h1>; }
function NotFound() { return <h1>404 - Page not found</h1>; }
export default 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 />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}(at /about) Home | About About me
URL Parameters with useParams
<Route path="/blog/:slug" element={<BlogPost />} />
function BlogPost() {
const { slug } = useParams();
return <h1>Reading: {slug}</h1>;
}(at /blog/react-hooks) Reading: react-hooks
Nested Routes and Layouts
A parent route can render shared layout, and an Outlet marks where child routes appear.
function DashboardLayout() {
return (
<div className="dashboard">
<aside>Sidebar</aside>
<Outlet />
</div>
);
}
<Route path="/dashboard" element={<DashboardLayout />}>
<Route index element={<Overview />} />
<Route path="settings" element={<Settings />} />
</Route>(at /dashboard/settings) Sidebar | Settings page
Navigating in Code
Use the useNavigate hook to redirect after an action such as logging in or saving a form: const navigate = useNavigate(); then navigate("/dashboard"). Pass { replace: true } to replace the current history entry.
Hosting Tip
Because routes exist only in JavaScript, your server must return index.html for every path. On Netlify add a _redirects file, on Apache an .htaccess rewrite, or on Vercel a rewrite rule; otherwise refreshing /about gives a 404.
Frequently asked questions
What is the difference between Link and an a tag in React Router?
An <a> tag reloads the whole page from the server. Link updates the URL and renders the new route in the browser, keeping app state and feeling instant.
How do I get URL parameters in React Router?
Define a dynamic segment like /users/:id and call useParams() in the component to get { id }.
Why do I get 404 when I refresh a React Router page?
Your server looks for a real file at that path. Configure it to serve index.html for all routes so React Router can handle the URL.