React ยท Chapter 29 of 42

Routing Basics

React itself has no built-in router. The most popular solution is React Router, which lets you map URL paths to components for building multi-page single-page applications (SPAs).

Routing enables navigation without full page reloads, keeping the experience fast and app-like.

Setting up routes

Wrap your app in `<BrowserRouter>`, then define `<Routes>` containing `<Route path="..." element={<Component />} />` for each page.

Navigation

Use `<Link to="/about">` instead of `<a href>` to navigate without a full page reload, preserving app state.

Example 1 (jsx)
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Link to="/about">About</Link>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}
Output
(navigates between Home and About without reloading)

Routes map URL paths to components, and Link enables client-side navigation.

Key points

  • React Router is the most common routing library for React.
  • BrowserRouter and Routes/Route define your app's paths.
  • Link enables navigation without full page reloads.
  • Routing enables SPA behavior with multiple 'pages'.
๐Ÿ’ก Note: React Router v6+ uses <Routes> and element props; older versions used <Switch> and component props.

๐Ÿ“ Quick Quiz

1. What library is most commonly used for routing in React?

2. What component enables client-side navigation without reload?

3. What wraps a React Router app to enable routing?