Routing with React Router

19.3

Map URLs to screens. Give each important screen an address that people can bookmark or share.

On this page

Add links and routes

Install react-router and wrap your route tree in BrowserRouter. Routes selects the matching route. NavLink shows which link is active. A path such as /products/:id captures the product ID for useParams.

import React from "react";
import { BrowserRouter, NavLink, Route, Routes, useParams } from "react-router";

function Product() {
  const { id } = useParams();
  return <h1>Product {id}</h1>;
}

export default function App() {
  return (
    <BrowserRouter>
      <nav>
        <NavLink to="/" end>Home</NavLink>{" "}
        <NavLink to="/products/42">Pen</NavLink>
      </nav>
      <Routes>
        <Route path="/" element={<h1>Inventory</h1>} />
        <Route path="/products/:id" element={<Product />} />
        <Route path="*" element={<h1>Page not found</h1>} />
      </Routes>
    </BrowserRouter>
  );
}

Serve direct page requests

When a user reloads /products/42, the request reaches the host first. Configure a single-page app fallback to index.html for client page paths, while keeping API and asset routes separate. Test a link, a direct reload, the Back button, and an unknown URL. A client-side not-found screen does not set the server’s HTTP status.

# Nginx: inside the server block for the SPA
location /products/ {
    try_files $uri $uri/ /index.html;
}

# Keep existing /api/ and asset locations separate.

Official references