Skip to content

Hands-on: Shopping Cart Exercise

You’ve now learned the basics of React. Let’s build a shopping cart component together.

Your goal is to recreate the shopping cart component below exactly.

Fruit Store 🍎

Cart
Total: $0
  • Create a new React page and bind it to the /cart route
  • Add a button on the home page that goes to /cart
  • GET the products data from https://junxuanb.com/api/products.json
  • Show the data for each product, where discount is the amount taken off the price
  • For products without a discount, simply show price
  • For discounted products, first strike through the original price, then highlight the real price. Calculate the real price as price minus discount.
  • Each product has an Add to cart button. Clicking it adds the product to the cart and reduces its stock
  • Each item in the cart has three buttons, +, - and Delete, to increase the quantity, decrease it and remove the item. Each action should update the stock accordingly
  • The bottom of the cart shows the total price, updated in real time
  • The bottom of the cart has a Check out button. Clicking it checks out the items in the cart and shows a message
  • Use Card for the layout, for each product and for the items in the cart
  • Use Flex so the product area wraps automatically
  • Use Typography for the strikethrough and the highlight
  • antd has many built-in Icons you can use for the +, - and Delete buttons
  • Use Message for the message shown at checkout

For Cherry, the real price should be 2.99 - 0.3 = 2.69. If you get 2.6900000000000004, that’s a floating-point precision issue in TypeScript. You can install decimal.js with npm install decimal.js and use it for decimal math, for example new Decimal(2.99).minus(0.3).toNumber()

When you change an array stored in useState, you may need to work on the array first and then save it. In that case, you need to make a copy first. For example:

const [cart, setCart] = useState<Product[]>([]);
const newCart = cart;
// ... do something with newCart, such as .forEach() or .push()
setCart(newCart);

This causes problems! newCart is only a reference to cart, so changing newCart really means trying to change cart directly, which isn’t allowed. Instead, we need:

const [cart, setCart] = useState<Product[]>([]);
const newCart = [...cart]; // make a new array instead of referencing the old one
// ... do something with newCart, such as .forEach() or .push()
setCart(newCart);

This avoids changing cart directly in a way that isn’t allowed.