Client-side routing with React router

A single-page app has one HTML document and updates the content with JavaScript. React Router intercepts link clicks, updates the browser URL with the history API, and renders a different component for each route. No full reload, no blank flash, just instant navigation.

App.tsx
tsx
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import { Home } from './pages/Home';
import { BookDetail } from './pages/BookDetail';
import { Login } from './pages/Login';

export function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/login">Login</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/books/:id" element={<BookDetail />} />
        <Route path="/login" element={<Login />} />
      </Routes>
    </BrowserRouter>
  );
}

Declare the routes once, let the Router pick the right component by URL.

Read it carefully. BrowserRouter sets up the routing context. Routes and Route declare the URL-to-component mapping. Link is the navigation primitive that updates the URL without a reload. Use Link instead of an a tag whenever you want instant client navigation.

Quiz: Quiz

Loading practice…