React Routing
Single-page apps still need URLs: a link to /products/42 should open that product, the back button should work, and users should be able to bookmark pages. Routing maps the current URL to the components to show — without reloading the page. React has no built-in router; the most popular choice is React Router.
How client-side routing works
- The app reads the current location (
/about, or#/aboutwith hash routing). - It picks the component that matches and renders it.
- Links change the URL with the History API instead of loading a new page.
- When the URL changes (link click, back button), the app re-renders the matching component.
Let's first build a tiny router ourselves to see that there's no magic. We use the hash (#/about) because changing it never reloads the page and works anywhere, including this playground. The Link component intercepts the click and sets location.hash itself — just like a real router's <Link> intercepts clicks and calls the History API:
import { useEffect, useState } from 'react';
function useHashPath() {
const read = () => window.location.hash.slice(1) || '/';
const [path, setPath] = useState(read);
useEffect(() => {
const onChange = () => setPath(read());
window.addEventListener('hashchange', onChange);
return () => window.removeEventListener('hashchange', onChange);
}, []);
return path;
}
function Link({ to, children }) {
function handleClick(e) {
e.preventDefault(); // don't let the browser follow the link
window.location.hash = to; // change only the hash → fires 'hashchange'
}
return <a href={`#${to}`} onClick={handleClick} style={{ marginRight: 12 }}>{children}</a>;
}
const Home = () => <h2>🏠 Home</h2>;
const About = () => <h2>ℹ️ About us</h2>;
const NotFound = ({ path }) => <h2>🤷 No page at "{path}"</h2>;
export default function App() {
const path = useHashPath();
let page;
if (path === '/') page = <Home />;
else if (path === '/about') page = <About />;
else page = <NotFound path={path} />;
return (
<div>
<nav><Link to="/">Home</Link><Link to="/about">About</Link><Link to="/missing">Broken link</Link></nav>
{page}
<small>Current path: {path}</small>
</div>
);
}Route parameters
Real routes contain variables, like /users/7. A small matcher can turn a pattern such as /users/:id into parameters:
import { useEffect, useState } from 'react';
function useHashPath() {
const read = () => window.location.hash.slice(1) || '/';
const [path, setPath] = useState(read);
useEffect(() => {
const onChange = () => setPath(read());
window.addEventListener('hashchange', onChange);
return () => window.removeEventListener('hashchange', onChange);
}, []);
return path;
}
function matchRoute(pattern, path) {
const p = pattern.split('/').filter(Boolean);
const s = path.split('/').filter(Boolean);
if (p.length !== s.length) return null;
const params = {};
for (let i = 0; i < p.length; i++) {
if (p[i].startsWith(':')) params[p[i].slice(1)] = decodeURIComponent(s[i]);
else if (p[i] !== s[i]) return null;
}
return params;
}
function Router({ routes }) {
const path = useHashPath();
for (const [pattern, Component] of routes) {
const params = matchRoute(pattern, path);
if (params) return <Component {...params} />;
}
return <p>404 — page not found</p>;
}
function Link({ to, children }) {
return <a href={`#${to}`} onClick={(e) => { e.preventDefault(); window.location.hash = to; }}>{children}</a>;
}
const USERS = { 1: 'Ha', 2: 'Kien', 3: 'Thu' };
function UserList() {
return (
<ul>
{Object.entries(USERS).map(([id, name]) => (
<li key={id}><Link to={`/users/${id}`}>{name}</Link></li>
))}
</ul>
);
}
function UserPage({ id }) {
const name = USERS[id];
if (!name) return <p>No user with id {id}. <Link to="/users">Back</Link></p>;
return <p>👤 User #{id}: <strong>{name}</strong> · <Link to="/users">All users</Link></p>;
}
export default function App() {
return (
<div>
<nav><Link to="/">Home</Link> | <Link to="/users">Users</Link> | <Link to="/users/99">User 99</Link></nav>
<Router
routes={[
['/', () => <h3>Welcome! Pick a user.</h3>],
['/users', UserList],
['/users/:id', UserPage],
]}
/>
</div>
);
}That's the core idea of every router: match the location, extract parameters, render. Production routers add nested layouts, data loading, redirects and much more.
React Router
Install it in a Vite project with npm install react-router. A typical setup (React Router v7, "declarative mode"):
// main.jsx
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router';
import App from './App.jsx';
createRoot(document.getElementById('root')).render(
<BrowserRouter>
<App />
</BrowserRouter>
);// App.jsx
import { Routes, Route, Link, NavLink, Outlet, useParams, useNavigate } from 'react-router';
function Layout() {
return (
<>
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/products">Products</NavLink>
</nav>
<Outlet /> {/* the matched child route renders here */}
</>
);
}
function Product() {
const { id } = useParams();
const navigate = useNavigate();
return (
<div>
<h2>Product {id}</h2>
<button onClick={() => navigate('/products')}>Back to list</button>
</div>
);
}
export default function App() {
return (
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="products" element={<ProductList />} />
<Route path="products/:id" element={<Product />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
);
}React Router essentials
| API | Purpose |
|---|---|
<BrowserRouter> |
provides routing using real URLs (/about) |
<HashRouter> |
uses #/about — works on static hosts without server config |
<Routes> / <Route path element> |
define which component renders for which path |
<Route index> |
the default child route |
path="*" |
catch-all, e.g. a 404 page |
<Link to> / <NavLink to> |
navigation links; NavLink knows if it's active |
<Outlet /> |
where nested routes render inside a layout |
useParams() |
read :id-style parameters |
useNavigate() |
navigate from code, e.g. after saving |
useSearchParams() |
read and update ?query=string values |
Note: With
BrowserRouter, your server must returnindex.htmlfor every path (otherwise reloading/products/7gives a 404). Static hosts usually have a "SPA fallback" setting for this.HashRouteravoids the problem.
Framework mode
React Router can also act as a full framework (formerly Remix), with route modules that export loader functions to fetch data before rendering, action functions for form submissions, and server rendering. Next.js offers similar features with file-based routing: a file app/products/[id]/page.jsx becomes the route /products/:id.
Test yourself
What does client-side routing avoid?
- Using URLs
- Full page reloads when navigating
- Rendering components
- The browser history
In React Router, how do you read the id from the route products/:id?
- props.id
- useParams().id
- window.id
- useRoute('id')
Which component marks where nested child routes render inside a layout?
- <Routes>
- <Link>
- <Outlet />
- <Switch>