generated from ibm-developer-skills-network/coding-project-template
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathCartItem.jsx
86 lines (69 loc) · 2.83 KB
/
CartItem.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { removeItem, updateQuantity } from './CartSlice';
import './CartItem.css';
const CartItem = ({ onContinueShopping }) => {
const cart = useSelector(state => state.cart.items);
const dispatch = useDispatch();
// Calculate total amount for all products in the cart
const calculateTotalAmount = () => {
let total = 0;
if (!cart || cart.length === 0) return total;
cart.forEach(item => {
// Extract cost (remove $ and convert to number)
const cost = parseFloat(item.cost.substring(1));
// Get quantity
const quantity = item.quantity || 0;
// Add to running total
total += cost * quantity;
});
// Return formatted total with 2 decimal places
return total.toFixed(2);
};
const handleContinueShopping = (e) => {
};
const handleIncrement = (item) => {
const updatedItem = { ...item, quantity: item.quantity + 1 };
dispatch(updateQuantity(updatedItem));
};
const handleDecrement = (item) => {
};
const handleRemove = (item) => {
};
// Calculate total cost based on quantity for an item
const calculateTotalCost = (item) => {
if (!item) return "0.00";
const cost = parseFloat(item.cost.substring(1));
return (cost * item.quantity).toFixed(2);
};
return (
<div className="cart-container">
<h2 style={{ color: 'black' }}>Total Cart Amount: ${calculateTotalAmount()}</h2>
<div>
{cart.map(item => (
<div className="cart-item" key={item.name}>
<img className="cart-item-image" src={item.image} alt={item.name} />
<div className="cart-item-details">
<div className="cart-item-name">{item.name}</div>
<div className="cart-item-cost">{item.cost}</div>
<div className="cart-item-quantity">
<button className="cart-item-button cart-item-button-dec" onClick={() => handleDecrement(item)}>-</button>
<span className="cart-item-quantity-value">{item.quantity}</span>
<button className="cart-item-button cart-item-button-inc" onClick={() => handleIncrement(item)}>+</button>
</div>
<div className="cart-item-total">Total: ${calculateTotalCost(item)}</div>
<button className="cart-item-delete" onClick={() => handleRemove(item)}>Delete</button>
</div>
</div>
))}
</div>
<div style={{ marginTop: '20px', color: 'black' }} className='total_cart_amount'></div>
<div className="continue_shopping_btn">
<button className="get-started-button" onClick={(e) => handleContinueShopping(e)}>Continue Shopping</button>
<br />
<button className="get-started-button1">Checkout</button>
</div>
</div>
);
};
export default CartItem;