Start learning free

LESSON 136 OF 161 · FRONTEND: FRONTEND WITH AI

The AI Copied Props into State in JavaScript

Practice

The Corner Shop runs a Kitchen week: a list of kitchen products, each drawn by a ProductCard, and a "Sale prices ($3 off)" checkbox. App holds the checkbox; when it is on, App sends each card a product whose price is $3 lower. An AI assistant wrote the card like this:

export default function ProductCard({ product }) {
  const [price] = useState(product.price);
  const [quantity, setQuantity] = useState(1);
  const total = price * quantity;
  …
      <span className="price"> ${price}</span>

It looks right when the page opens: the Mug shows $12. But useState(product.price) uses its argument only at the card's first draw. When the visitor ticks the sale box, App sends a Mug at $9, and the AI's card keeps showing its old copy: Mug $12. The state is a snapshot; the prop is the live value.

A smaller example: a greeting that copies its prop with const [shown] = useState(name) keeps saying "Hi, Ana" after the parent sends name="Bo", while Hi, {name} follows the prop. Keep in state only what the component itself changes, like the quantity its + button raises. Work out everything else with a plain const at each draw.

The check opens the page, clicks "One more Mug", then ticks and unticks the sale box. Your cards must show:

item: Mug $12 × 1 = $12
item: Teapot $22 × 1 = $22
> click "One more Mug"          →  item: Mug $12 × 2 = $24
> click "Sale prices ($3 off)"  →  item: Mug $9 × 2 = $18, item: Teapot $19 × 1 = $19
> click "Sale prices ($3 off)"  →  item: Mug $12 × 2 = $24, item: Teapot $22 × 1 = $22

Your task: in src/ProductCard.jsx, show the price straight from product.price, work out the total from product.price and quantity, and show the quantity and the total.


Assignment
Follow the Coding Tutorial to rewrite the AI's ProductCard so it reads the price from its prop at every draw.


Hint
Only quantity belongs in state: the card's own + button changes it. The price comes from the parent, so read product.price wherever you need it.


STEP 1 OF 3
    Ctrl + Enter to check

    Aiui Copied Props in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free