Skip to lesson content

PROJECT 2 · LESSON 4 OF 18

Render products from a file

Build a catalog from one data source and one reusable card.

  • data modules
  • map
  • keys
  • typed props

Your workspace: edushop

Continue from lesson 3: Refactor cards and add interaction. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

A real catalog changes more often than its card design. We want adding a product to mean adding data, not copying JSX. This lesson introduces a model, a reusable view and a page that joins them.

Product objects describe the data; ProductCard describes how one object appears. A catalog maps the array into cards. Adding data should not require editing the page markup.

Prices use integer paise to avoid introducing rounding errors in ordinary addition. Formatting for display happens at the edge of the UI.

Separate the product model from its appearance

Product describes the fields one card and one details page need: id, slug, name, price, category and description. id is a stable identity for application operations. slug is a human-readable URL segment. The name is display text and can change without requiring the ID to change.

TypeScript checks code against this shape while developing. It does not automatically validate external JSON or a user request at runtime. Our hard-coded array is trusted source data for this stage; later lessons add validation at network and storage boundaries.

Understand map and key using real records

products.map calls the rendering function once per object and returns an array of ProductCard elements. Each receives one product prop. ProductCard does not need to know how many products exist or where the list came from. The page handles the collection; the card handles one item.

The key helps React identify siblings when records are inserted, removed or reordered. It is not a visible product number and is not passed as a normal prop to the card. A stable product ID is appropriate. An array position can identify the wrong item after sorting.

Store money in minor units and format at display time

The notebook’s price is 24900 paise, equivalent to ₹249.00. Two notebooks cost 49800 paise. Keeping calculations in integer minor units avoids the common floating-point surprises of repeatedly adding fractional currency amounts.

money divides by 100 only when formatting the result for display with Intl.NumberFormat. Keep the stored number separate from its formatted string. A value such as ₹249.00 is for a reader, not a useful input to arithmetic.

This file-backed catalog is rebuilt from source. Editing the exported array during development is different from allowing a visitor to edit products persistently. A server process variable is not a database and changes to it would not be a reliable multi-user store.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The /products page imports the product array.

  2. map creates one ProductCard element per product.

  3. Each card formats its price and builds its details URL from the slug.

  4. The rendered grid displays the three records; the next lesson implements the details destination.

Turn one record into one card

  1. Select the object with id p1. Its name becomes the card heading.
  2. Its slug learning-notebook becomes /products/learning-notebook in the Link.
  3. Its price 24900 becomes ₹249.00 through money.
  4. The card key is p1. Changing the display name does not require changing the ID or the rendering loop.

3. Build it, one file at a time

  1. Continue in the same EduShop folder. Add these files.
  2. Add a Products link to the navigation in app/layout.tsx.
  3. Open /products. Product links become working details routes in the next lesson.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

lib/products.ts

This defines the plain product shape and the initial read-only catalog.

lib/products.ts
export type Product = {
  id: string;
  slug: string;
  name: string;
  price: number;
  category: string;
  description: string;
};
// Prices are integer paise: 24900 means ₹249.00.
export const products: Product[] = [
  {
    id: "p1",
    slug: "learning-notebook",
    name: "Learning notebook",
    price: 24900,
    category: "stationery",
    description: "A notebook for diagrams and project notes.",
  },
  {
    id: "p2",
    slug: "desk-lamp",
    name: "Desk lamp",
    price: 89900,
    category: "desk",
    description: "Light up your practice workspace.",
  },
  {
    id: "p3",
    slug: "pen-set",
    name: "Pen set",
    price: 9900,
    category: "stationery",
    description: "Three pens for everyday learning.",
  },
];

Read the code

  1. Product is a TypeScript type; it is erased at runtime. The exported products array contains the actual values used by the pages.
  2. id identifies a product in state and lists. slug identifies it in a human-readable URL. Make both unique.
  3. price is an integer number of paise. Keep that unit consistent in the cart and formatter.

lib/money.ts

This converts a numeric amount into a readable rupee string at the presentation boundary.

lib/money.ts
export function money(paise: number) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
  }).format(paise / 100);
}

Read the code

  1. The input is paise. Dividing by 100 converts it to rupees before formatting.
  2. Intl.NumberFormat applies currency formatting such as grouping and two decimal places. The returned string is display text, not a value to store back into numeric price fields.

components/product-card.tsx

This renders one product without owning catalog loading or filtering.

components/product-card.tsx
import Link from "next/link";
import type { Product } from "@/lib/products";
import { money } from "@/lib/money";
export default function ProductCard({ product }: { product: Product }) {
  return (
    <article>
      <h2>
        <Link href={`/products/${product.slug}`}>{product.name}</Link>
      </h2>
      <p>{product.description}</p>
      <strong>{money(product.price)}</strong>
    </article>
  );
}

Read the code

  1. import type brings in the Product contract without importing runtime data. The product prop supplies the actual record.
  2. The Link uses the product slug to construct its details URL. money formats its integer price.
  3. The parent gives each repeated card a key. The key is used by React for sibling identity and is not automatically available as a normal card prop.

app/products/page.tsx

This page owns collection-level loading and renders one reusable card per resulting product.

app/products/page.tsx
import { products } from "@/lib/products";
import ProductCard from "@/components/product-card";
export default function ProductsPage() {
  return (
    <>
      <h1>Products</h1>
      <div className="grid">
        {products.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>
    </>
  );
}

Read the code

  1. map creates ProductCard elements, each with one product prop and a stable id key. ProductCard does not fetch its own list.
  2. The source is the imported product array. Adding a record changes the list without changing the loop.

app/layout.tsx

This defines the document and shared structure surrounding the selected page.

app/layout.tsx
import type { ReactNode } from "react";
import Link from "next/link";
import "./globals.css";
export const metadata = {
  title: "EduShop",
  description: "My Next.js learning project",
};
export default function Layout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <nav>
          <Link href="/">Home</Link>
          <Link href="/products">Products</Link>
          <Link href="/about">About</Link>
          <Link href="/contact">Contact</Link>
        </nav>
        <main>{children}</main>
      </body>
    </html>
  );
}

Read the code

  1. html and body belong to this root layout. children is the selected route content and must appear in the returned tree.
  2. Shared navigation belongs here so individual pages do not copy it. Link destinations are URL paths, not source filenames.
  3. The stylesheet import applies the shared presentation. The metadata export describes the document rather than rendering visible content.

4. Run it and check your result

  • Three products appear with rupee prices.
  • Adding a fourth object to products adds a fourth card.

5. Predict, change and observe

Add a fourth object, then reverse the order of the array.

Compare your prediction with the expected result

What you should observe

Four cards appear in the new array order without changing ProductCard.

Why it happens

The page derives the UI from data. Stable keys retain the identity of each record even when its position changes.

6. Troubleshoot with evidence

A common mistake

Use the product ID as key, not the array position. This file is a read-only data source, not a persistent database.

Prices are one hundred times smaller than expected.

Likely cause: Rupee values were entered where paise are required.

Check and correct: Store 24900 for ₹249.00. Do not remove the division in the formatter to hide inconsistent data.

React reports duplicate keys.

Likely cause: Two products have the same ID.

Check and correct: Give every product a unique stable ID. Also keep slugs unique so details routes identify one product.

7. Practice and explain it back

Your independent task

Add a category label to the card and a new product with a unique ID and slug.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why pass a whole product to the card?

The card needs several fields from the same record. A typed product prop keeps that contract explicit and reusable.

Can a database replace the file without changing every card?

Yes. If the database layer returns the same plain product shape, the page can supply those objects to the existing card.