Skip to main content
Albero Academy

Routing with React Router

Turn a single-page app into many pages — routes, links, URL params, nested layouts and programmatic navigation.

Chapter 13React15 min readBeginner friendly
  • #React
  • #Routing
  • #React Router

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

define routes
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

dynamic segments
<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 />:

shared layout
<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
}
navigate in code
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

  1. 01Client-side routing renders components by URL with no full reload — back/forward/bookmarks still work.
  2. 02React Router: <Routes>/<Route> map paths to elements; <Link> navigates (never a plain <a>).
  3. 03Dynamic segments (/:slug) are read with useParams; query strings with useSearchParams.
  4. 04Nested routes share a layout, rendering children at <Outlet />.
  5. 05useNavigate() navigates programmatically after actions.