CartItem.jsx 1.96 KB
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