CodeBlanks Logo Icon CodeBlanks

Challenge: Routed cart

Write product list, detail and cart routes with React Router.

Challenge: Routed cart

In this challenge you set up a shopping cart app with React Router. The / route shows the product list; the /cart/:id route shows a single product.

Use useParams to read the id from the URL; find the product with products.find(p => p.id === id). Define routes inside <Routes>.

This is the basic skeleton of e-commerce sites.

Practice Routed cart

Write ProductList: render a <ul> with <li>s listing products. Write ProductPage: get id with useParams(), find the product with products.find(p => p.id === Number(id)), render <h1>{product.name}</h1>. Write CartApp: inside <BrowserRouter> define <Routes> with path="/" element <ProductList /> and path="cart/:id" element <ProductPage />. export default CartApp.

Starter code

App.jsx
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";

const products = [{ id: 1, name: "Kalem" }, { id: 2, name: "Defter" }];

// ProductList, ProductPage, CartApp bileşenlerini buraya yaz

Sample solution

App.jsx
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";

const products = [{ id: 1, name: "Pen" }, { id: 2, name: "Notebook" }];

function ProductList() {
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  );
}

function ProductPage() {
  const { id } = useParams();
  const product = products.find((p) => p.id === Number(id));
  return <h1>{product.name}</h1>;
}

function CartApp() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<ProductList />} />
        <Route path="cart/:id" element={<ProductPage />} />
      </Routes>
    </BrowserRouter>
  );
}

export default CartApp;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which hook reads the id from the URL?

  • useParams Correct answer
  • useState
  • useNavigate
  • useLocation

Explanation: useParams returns URL parameters.

2 Route path

Question
<Route path="____" element={<ProductPage />} />
Answer
<Route path="cart/:id" element={<ProductPage />} />

Explanation: :id declares a URL parameter.

All lessons in Intermediate