ProductCard.jsx
1.88 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
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