A React app is one HTML page, but users expect multiple URLs — /programs, /pricing, /programs/data. Client-side routing swaps the rendered component based on the URL without a full page reload. The standard tool is React Router.
Client-side routing
The router watches the URL and renders the matching component, updating the address bar and browser history — so back/forward and bookmarks all work, but navigation is instant (no server round-trip for the page shell).
Routes & links
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";function App() {return (<BrowserRouter><nav><Link to="/">Home</Link><Link to="/programs">Programs</Link></nav><Routes><Route path="/" element={<Home />} /><Route path="/programs" element={<Programs />} /><Route path="*" element={<NotFound />} /> {/* catch-all 404 */}</Routes></BrowserRouter>);}
URL params
<Route path="/programs/:slug" element={<Program />} />function Program() {const { slug } = useParams(); // "data-analytics"const [search] = useSearchParams(); // ?tab=curriculum// …fetch the programme by slug}
Nested routes & layouts
Nest routes to share a layout (a sidebar, a shell) across pages, rendering the child where you put an <Outlet />:
<Route path="/dashboard" element={<DashboardLayout />}><Route index element={<Overview />} /> {/* /dashboard */}<Route path="courses" element={<Courses />} /> {/* /dashboard/courses */}</Route>function DashboardLayout() {return <div><Sidebar /><main><Outlet /></main></div>; // child renders here}
Programmatic navigation
import { useNavigate } from "react-router-dom";function EnrolButton() {const navigate = useNavigate();const handle = async () => {await enrol();navigate("/dashboard"); // go after an action};}
Practice
Set up routes for Home, a Programs list, a /programs/:slug detail page (read the param), and a 404. Add a shared layout with a nav via nested routes and <Outlet />, and navigate programmatically after a button click.
Key takeaways
- 01Client-side routing renders components by URL with no full reload — back/forward/bookmarks still work.
- 02React Router: <Routes>/<Route> map paths to elements; <Link> navigates (never a plain <a>).
- 03Dynamic segments (/:slug) are read with useParams; query strings with useSearchParams.
- 04Nested routes share a layout, rendering children at <Outlet />.
- 05useNavigate() navigates programmatically after actions.
