Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 50 ยท Projects

Project: A Product Catalog with Filters and a Cart

Build a shop with React Router ideas: filters and sorting stored in the URL, product detail routes, a cart that survives navigation, and a deep-linkable quick-view modal route.

Almost every shop has the same four screens: a grid of products, a way to narrow it down, a page for one product, and a cart. They make a good router project because each screen asks a different question about where state should live. The filters belong in the URL, so a visitor can bookmark "lamps under $100, cheapest first" or send it to a friend. The product belongs in a route parameter, so every product has an address. The cart belongs in memory above the router, so it survives moving between pages. And the quick-view popup belongs partly in both: it has its own address, yet it appears on top of the page you were browsing.

You will build all four in two steps, using the small hash router that powers the live examples in this tutorial, and then see how each piece looks in real React Router code. Background reading: Search Params, Putting UI State in the URL, Dynamic Segments and Modal Routes.

Real library or stand-in? The runnable code uses a hand-written router (about 130 lines) with route objects, nested layouts with Outlet, useParams, useSearchParams, NavLink and a go(to, state) function that works like navigate(to, { state }). React Router itself cannot be installed in the live editor, so the real versions of the same ideas are in read-only blocks. One honest difference: the real router keeps navigation state in the browser's history entry, while the stand-in keeps it in a variable, so it does not survive the Back/Forward buttons.

What belongs in the URL?

A useful test: would a visitor want to share, bookmark or reload this? If yes, it belongs in the URL. If it is private, short-lived or only meaningful inside one component, keep it in state.

State Where Why
Category, sort, price limit, search text Search params (?cat=lamps&sort=price-asc) Shareable, reloadable, Back button undoes it
Which product is shown Route param (/product/3) Every product has its own page and title
Cart contents State above the router (context) Private, and must survive route changes
Is the quick-view popup open The URL (/product/3) plus a background Deep-linkable, closes with Back
Text typed in the search box Local state, mirrored to the URL Typing must stay responsive

Defaults are left out of the URL. cat=all or sort=featured would only make links longer and give the same page two different addresses, so the code removes a parameter whenever its value equals the default.

flowchart LR
    A["URL with a query string<br/>such as ?cat=lamps"] --> B["readFilters(params)"]
    B --> C["filterProducts(PRODUCTS, filters)"]
    C --> D["grid of cards"]
    E["user changes a select"] --> F["setParams(next)"]
    F --> A

The filters are never copied into component state. The URL is the single source of truth, and the grid is a pure function of it.

Step 1: filters in the URL

The heart of the catalog is one pure function, filterProducts, which takes the product list and the filter values and returns the products to show. It knows nothing about React or the URL, so you could unit test it with plain arrays. A second small function, readFilters, turns URLSearchParams into those values and fills in the defaults. Everything the page shows is computed from those two functions during render.

Updating a filter does the reverse: copy the current params, set or delete one key, and navigate to the new query string. Typing in the search box is the one case where pushing a history entry for every letter would be annoying, so that input keeps its own text state for responsiveness and replaces the current history entry instead of adding one (the stand-in uses location.replace for this; real React Router has { replace: true }).

Try it: change the category, drag the price slider and type "desk". In a normal browser tab, Back and reload would now restore exactly these filters, because they are in the address. The sandboxed preview hides its address, but the line under the controls always shows what the current filters produce.

Step 1: a catalog whose filters live in the URL

The same page with the real React Router (read-only). useSearchParams returns the params and a setter, and the setter accepts a function so that several controls cannot overwrite each other with stale values:

JSX
// Catalog.jsx - React Router (read-only)
import { useSearchParams } from 'react-router';

export default function Catalog() {
  const [searchParams, setSearchParams] = useSearchParams();
  const filters = readFilters(searchParams);
  const products = filterProducts(PRODUCTS, filters);

  function update(key, value, replace = false) {
    setSearchParams(
      (previous) => {
        const next = new URLSearchParams(previous);
        if (value === DEFAULTS[key] || value === '') {
          next.delete(key);
        } else {
          next.set(key, value);
        }
        return next;
      },
      { replace },
    );
  }

  return (/* the same controls and grid as in the live example */);
}

In data mode you can move the filtering into a loader: new URL(request.url).searchParams gives the same values, and the router re-runs the loader whenever the query string changes. That is the better choice when the products come from a server. For a small client-side list, filtering during render is simpler and instant.

Step 2: detail routes, the cart and a modal route

The next version adds three things.

A detail route. product/:id shows one product. The component reads id with useParams, looks the product up and, because the id comes from the outside world, handles the case where it does not exist. The links on the cards point to this route.

A cart. The cart is plain React state in a context provider placed above the routes, so switching from the catalog to the cart page does not reset it. The header shows the item count and the cart page can change quantities. Nothing about the cart is stored in the URL: a shared cart link would be a privacy and consistency problem.

A modal route. "Quick view" opens the product in a popup over the catalog, and the popup has its own address, /product/3. How can one URL render two different things? By remembering where the user came from. The link navigates with a background location in the navigation state, and the app renders the routes twice: once for the background (so the catalog stays visible and keeps its filters) and once for the real URL, inside the dialog. If someone opens /product/3 directly, there is no background and the same route renders as a normal full page. That is why the product component takes an inModal flag and nothing else changes.

flowchart TD
    A["Click Quick view<br/>go('/product/3', background: current URL)"] --> B{"navigation state has a background?"}
    B -- yes --> C["Routes render the background URL<br/>(catalog with its filters)"]
    B -- yes --> D["Routes render the real URL<br/>inside a dialog"]
    B -- no --> E["Routes render the real URL<br/>as a full page"]

Quick view and the full page are the same route. With a background, both the catalog and the dialog render; without one, only the full page does.

Things to try in the example: click Add on a few cards and watch the header count; use Quick view and press Escape or Close (you return to the same filters); open a product name for the full page; open the Cart and change quantities.

Step 2: the full shop with detail routes, a cart and a modal route

The important line is in App: <Routes routes={routes} url={background ?? url} />. Without a background, the first Routes shows the real URL and no dialog appears. With one, the first Routes keeps showing the catalog (with its filters, because the background URL still has the query string), and the second renders only the product inside the dialog.

The real React Router version

Detail route and cart link. In a real app you would build the links with Link, which handles the click without a full page load (see Link and NavLink):

JSX
// Layout.jsx - React Router (read-only)
import { NavLink, Outlet } from 'react-router';
import { useCart } from './cart';

export default function Layout() {
  const { count } = useCart();
  return (
    <>
      <header>
        <NavLink to="/" end>Catalog</NavLink>
        <NavLink to="/cart">Cart ({count})</NavLink>
      </header>
      <Outlet />
    </>
  );
}

The modal with a background location. In declarative mode the pattern is documented and short. A Link passes the current location as state, and the app renders <Routes> twice:

JSX
// App.jsx - React Router (read-only)
import { Link, Route, Routes, useLocation, useNavigate } from 'react-router';

function ProductCard({ product }) {
  const location = useLocation();
  return (
    <Link to={'/product/' + product.id} state={{ background: location }}>
      Quick view
    </Link>
  );
}

export default function App() {
  const location = useLocation();
  const navigate = useNavigate();
  const background = location.state?.background;

  return (
    <>
      <Routes location={background ?? location}>
        <Route path="/" element={<Layout />}>
          <Route index element={<Catalog />} />
          <Route path="product/:id" element={<ProductDetail />} />
          <Route path="cart" element={<CartPage />} />
        </Route>
      </Routes>

      {background && (
        <Routes>
          <Route
            path="/product/:id"
            element={
              <Modal onClose={() => navigate(-1)}>
                <ProductDetail inModal />
              </Modal>
            }
          />
        </Routes>
      )}
    </>
  );
}

Note that the real version closes the modal with navigate(-1): the dialog was opened by a push, so going back is exactly "undo the open". That only works when the modal was opened from inside the app, which is true here, because a background exists only after a click. For visitors who land on the URL directly, build the dialog's Close button so it links to a sensible parent (the catalog) when background is missing. The stand-in avoids the question by jumping to the background URL.

A data-router alternative. With createBrowserRouter there is no location prop for Routes. A common design is to nest the modal as a child route of the catalog: the catalog's route renders its own <Outlet />, and the child route product/:id renders the dialog into it. The catalog stays mounted behind the child, and the child can have its own loader. The trade-off is that a direct visit to /products/3 always shows the catalog behind the dialog. Both designs are valid; pick the one that matches what a deep link should look like. See Modal Routes and Background Locations for the details.

Ideas to extend it

  • Store the cart in localStorage in a real app (not possible in this sandbox) and read it once when the provider mounts.
  • Add pagination with a page search param, and reset it to 1 whenever another filter changes.
  • Turn the filtering into a loader and add a pending indicator with useNavigation (Pending and Optimistic UI).
  • Set document.title per route (Scroll Restoration, Focus and Page Titles), and move focus into the dialog (the stand-in already does this) and back to the "Quick view" link when it closes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the catalog remove a search param when its value equals the default?

    cat=all and no cat at all show the same page. Leaving defaults out keeps one canonical URL per view, which is better for sharing, caching and analytics.
  2. 2. Where should the cart live in this project, and why?

    Route components unmount when you leave their page, so state kept inside them is lost. The cart is private data, so it should not go into a URL. A provider above the router keeps it alive.
  3. 3. How can one URL, /product/3, render both as a full page and as a popup over the catalog?

    The route is the same. The link passes the current location as state. The app renders the routes for the background location, plus the real route inside a dialog. A direct visit has no state, so only the full page renders.
  4. 4. A visitor types in the search box. Why does the code replace the history entry instead of pushing a new one?

    Each push creates a history entry. After typing a word, the user would have to press Back once per letter. Replacing keeps the URL current without cluttering the history.
  5. 5. In real React Router, what does location.state survive that a plain variable would not?

    React Router keeps the state in the history entry (history.state), so it comes back with Back, Forward and reload. A new tab starts with no state, which is why a direct visit shows the full page.

Summary

  • Put shareable view state in the URL: filters and sorting in search params, the selected item in a route param. Keep private data such as the cart in state above the router.
  • Derive the visible list from the URL with a pure function. Never copy URL values into component state, apart from a text box that needs to stay responsive.
  • Omit default values from the URL so every view has one address, and use replace for rapid changes such as typing.
  • A modal route is the same route rendered over a background location passed in navigation state. Without that state it is a normal page, so deep links keep working.
  • Handle ids that match no product, and give the dialog role="dialog", focus and an Escape handler.

Next: Exercises: Declarative Routing