CodeBlanks Logo Icon CodeBlanks

List and detail

Write the product list and detail pages.

List and detail

The third lesson adds the product list and detail pages. The list renders an array of products as links; the detail reads id with useParams and shows the matching product.

A list item uses the Link component with a to attribute to link to the detail page. The detail component reads the id from the URL with useParams.

If the product is not found, the detail shows a gentle message; this informs the user about a broken link.

Detail page

The detail page reads the URL parameter with useParams and finds the matching product. Example: const { id } = useParams(); then filter the products array.

If the product is not found, showing a 'not found' message is a good practice. It gently informs the user about a broken link.

This pattern provides a consistent transition between list and detail pages; the user reaches the right content even when typing the path manually.

Practice Product list

Complete the skeleton below. Write a ProductList component; take { products }, render a ul with products.map producing an <li><Link to={`/product/${p.id}`}>{p.name}</Link></li> for each. Export it.

Starter code

App.jsx
import { Link } from "react-router-dom";

// Write the ProductList component here

Sample solution

App.jsx
import { Link } from "react-router-dom";

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

export default ProductList;

Questions and answers

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

1 How does the list link to detail?

  • <Navigate>
  • <a href>
  • <Route>
  • <Link to> Correct answer

Explanation: Link to provides the link to the detail page.

2 Using Link

Question
import { Link } from "react-router-dom";

<li key={p.id}><____ to={`/product/${p.id}`}>{p.name}</Link></li>
Answer
import { Link } from "react-router-dom";

<li key={p.id}><Link to={`/product/${p.id}`}>{p.name}</Link></li>

Explanation: Link to goes to the detail page.

3 List and detail: match the terms

Term Meaning
Link Creates a link
useParams Reads the id
to={`/product/${id}`} Detail path
products.find Finds the product

All lessons in Intermediate