React: A product card with a default prop

Make a reusable card whose optional prop has a sensible default.

What to build

Product cards that show a discounted price when there is a discount.

Requirements

  • Write ProductCard with the props name, price and discount (a percentage, default 0). It renders a div with the class card, an h3 with the name and a p with the class price showing $ and the final price with two decimals.
  • Only when the discount is more than 0, also render a span with the class badge and the text -D% (for example -20%).
  • App renders three cards: Notebook 4.5 with no discount, Backpack 40 with 20% off, and Pen 1.2 with 50% off.

Constraints

Do not pass discount={0}; rely on the default.

Example

The cards show "$4.50", then "$32.00" with "-20%", then "$0.60" with "-50%".

Why it works

A default value lets the common case leave the prop out, and the badge appears only when the data calls for it.

Hints

Hint 1

function ProductCard({ name, price, discount = 0 }) gives discount a default.

Hint 2

The final price is price × (100 − discount) / 100; show it with toFixed(2).

Solution

Show one correct solution (try it yourself first)
function ProductCard({ name, price, discount = 0 }) {
  const final = (price * (100 - discount)) / 100;
  return (
    <div className="card">
      <h3>{name}</h3>
      <p className="price">${final.toFixed(2)}</p>
      {discount > 0 ? <span className="badge">-{discount}%</span> : null}
    </div>
  );
}

export default function App() {
  return (
    <div>
      <ProductCard name="Notebook" price={4.5} />
      <ProductCard name="Backpack" price={40} discount={20} />
      <ProductCard name="Pen" price={1.2} discount={50} />
    </div>
  );
}

Lesson: Props: passing data to components →