CartItem.jsx
1.96 KB
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
import React from 'react'
import { Link } from 'react-router-dom'
import { useCart } from '../../context/CartContext'
const CartItem = ({ item }) => {
  const { updateCartItem, removeFromCart } = useCart()
  const handleQuantityChange = (newQuantity) => {
    if (newQuantity < 1) return
    if (newQuantity > 10) {
      alert('Maximum quantity is 10')
      return
    }
    updateCartItem(item.product._id, newQuantity)
  }
  const handleRemove = () => {
    if (window.confirm('Are you sure you want to remove this item?')) {
      removeFromCart(item.product._id)
    }
  }
  const subtotal = item.price * item.quantity
  return (
    <div className="cart-item">
      <div className="item-image">
        <Link to={`/products/${item.product._id}`}>
          <img 
            src={item.product.image} 
            alt={item.product.name}
            onError={(e) => {
              e.target.src = '/placeholder-image.jpg'
            }}
          />
        </Link>
      </div>
      
      <div className="item-details">
        <Link to={`/products/${item.product._id}`} className="item-name">
          <h4>{item.product.name}</h4>
        </Link>
        <p className="item-category">{item.product.category}</p>
        <p className="item-price">${item.price}</p>
      </div>
      
      <div className="item-quantity">
        <button 
          onClick={() => handleQuantityChange(item.quantity - 1)}
          disabled={item.quantity <= 1}
        >
          -
        </button>
        <span>{item.quantity}</span>
        <button 
          onClick={() => handleQuantityChange(item.quantity + 1)}
          disabled={item.quantity >= 10}
        >
          +
        </button>
      </div>
      
      <div className="item-subtotal">
        ${subtotal.toFixed(2)}
      </div>
      
      <div className="item-actions">
        <button onClick={handleRemove} className="remove-button">
          Remove
        </button>
      </div>
    </div>
  )
}
export default CartItem