Shopping Cart

MediumReact Components20 min5 tests

Build a shopping cart with three products. Each product has an "Add" button that increases its quantity, each cart line has decrement/increment buttons, and a live status region shows the total item count and total price. Removing the last unit of a line removes that line entirely.

You are building a small Shopping Cart widget.

There are three products, each with a fixed price:

| Product | Price |
| ------- | ----- |
| Apple | $10 |
| Bread | $5 |
| Milk | $15 |

Product list

  • Each product shows its name and price and has an "Add {name}" button (e.g. Add Apple).
  • Clicking the Add button increases that product's quantity in the cart by 1.

Cart

  • The cart shows one line per product that has a quantity of at least 1.
  • Each cart line shows the product name and its current quantity, plus a decrement button (aria-label="Decrease {name}") and an increment button (aria-label="Increase {name}").
  • Increment raises the quantity by 1; decrement lowers it by 1.
  • When a line's quantity would drop to 0, that line is removed from the cart entirely.

Status

  • A live region with role="status" always shows the current totals in the exact format:

"{count} items - ${total}" — for example "3 items - $45".

  • count is the total number of units across all lines; total is the summed price of every unit.
  • Use the singular word item when the count is exactly 1 (e.g. "1 item - $10"); use items otherwise (including "0 items - $0").

The starter renders the product list and an empty-cart shell but does not implement any of the cart behavior — your job is to make it work.

Requirements

  • Render an "Add {name}" button for each of the three products (Apple $10, Bread $5, Milk $15).
  • Clicking "Add {name}" increases that product's cart quantity by 1 and shows a cart line for it.
  • Each cart line has a decrement button (aria-label "Decrease {name}") and an increment button (aria-label "Increase {name}") that adjust the quantity by 1.
  • A role="status" region always shows "{count} items - ${total}" using the live totals, with singular "item" only when count is exactly 1.
  • When a line's quantity drops to 0, the line is removed from the cart.
Hints (3)
  1. Keep cart state as a map/object of productId -> quantity. Derive the count, total, and visible lines from that single source of truth on each render.
  2. For the status text, compute count and total by summing over the entries; choose the word 'item' vs 'items' with a simple ternary on count === 1.
  3. Decrementing should set the new quantity; if it reaches 0, remove that key from the state object so the line disappears instead of showing a zero line.

Topics

  • React
  • React Components

Asked at

Urban Company · Unacademy · Myntra · Ola · Meesho · Paytm

Join Us
blur