ProductCard.jsx 1.88 KB
import React from 'react'
import { Link } from 'react-router-dom'
import { useCart } from '../../context/CartContext'
import toast from 'react-hot-toast'

const ProductCard = ({ product }) => {
  const { addToCart } = useCart()

  const handleAddToCart = async () => {
    try {
      await addToCart(product._id, 1)
      toast.success('Product added to cart!')
    } catch (error) {
      toast.error('Failed to add product to cart')
    }
  }

  return (
    <div className="product-card">
      <Link to={`/products/${product._id}`} className="product-image">
        <img 
          src={product.image || '/placeholder-image.jpg'} 
          alt={product.name}
          onError={(e) => {
            e.target.src = '/placeholder-image.jpg'
          }}
        />
      </Link>
      
      <div className="product-info">
        <Link to={`/products/${product._id}`} className="product-name">
          <h3>{product.name}</h3>
        </Link>
        
        <p className="product-category">{product.category}</p>
        
        <div className="product-price">
          ${product.price}
          {product.originalPrice && (
            <span className="original-price">${product.originalPrice}</span>
          )}
        </div>
        
        <div className="product-rating">
          {Array.from({ length: 5 }).map((_, index) => (
            <span 
              key={index}
              className={`star ${index < (product.rating || 0) ? 'filled' : ''}`}
            >

            </span>
          ))}
          <span className="rating-count">({product.reviewCount || 0})</span>
        </div>
        
        <button 
          onClick={handleAddToCart}
          className="add-to-cart-button"
          disabled={!product.inStock}
        >
          {product.inStock ? 'Add to Cart' : 'Out of Stock'}
        </button>
      </div>
    </div>
  )
}

export default ProductCard