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 🍎
Total: $0
Requirements
Section titled “Requirements”- Create a new React page and bind it to the
/cartroute - Add a button on the home page that goes to
/cart
The /cart page
Section titled “The /cart page”GETtheproductsdata fromhttps://junxuanb.com/api/products.json- Show the data for each product, where
discountis 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
priceminusdiscount. - Each product has an
Add to cartbutton. Clicking it adds the product to the cart and reduces its stock - Each item in the cart has three buttons,
+,-andDelete, 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 outbutton. 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
+,-andDeletebuttons - Use Message for the message shown at checkout
Floating-point precision
Section titled “Floating-point precision”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()
Copying arrays
Section titled “Copying arrays”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.