CodeBlanks Logo Icon CodeBlanks

Challenge: Cart summary

Write a summary component that computes the total price from a product list.

Challenge: Cart summary

This challenge asks you to write a CartSummary component. The items prop is an array of objects, each { '{ name, price, qty }' }. Show the total amount and item count.

For the total, use reduce: items.reduce((sum, i) => sum + i.price * i.qty, 0). For the count, use items.length.

Show <p>{ '{ total }' } TL</p> and <p>{ '{ count }' } items</p>. For an empty cart, show <p>Cart is empty</p> via early return.

Practice Write CartSummary

Complete the skeleton. Write a CartSummary component. Take ({ '{ items }' }) as parameter. If items.length === 0, early return <p>Cart is empty</p>. Compute total with reduce and count with items.length. Show <p>{ '{ total }' } TL</p> and <p>{ '{ count }' } items</p>. Export it.

Starter code

App.jsx
// Write the CartSummary component here

Sample solution

App.jsx
function CartSummary({ items }) {
  if (items.length === 0) return <p>Cart is empty</p>;
  const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  const count = items.length;
  return (
    <div>
      <p>{total} TL</p>
      <p>{count} items</p>
    </div>
  );
}

export default CartSummary;

Questions and answers

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

1 Which method computes the total?

  • map
  • forEach
  • filter
  • reduce Correct answer

Explanation: reduce computes the total.

2 Match the cart computations

Term Meaning
reduce Total
length Item count
price * qty Line total
0 Initial value

All lessons in Beginner