|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useState } from 'react' |
| 4 | +import { formatCurrencyString } from 'use-shopping-cart' |
| 5 | +import { useShoppingCart } from 'use-shopping-cart' |
| 6 | + |
| 7 | +export default function Product({ product }) { |
| 8 | + const { addItem } = useShoppingCart() |
| 9 | + const { name, price, emoji } = product |
| 10 | + const [quantity, setQuantity] = useState(1) |
| 11 | + |
| 12 | + const decreaseQuantity = () => { |
| 13 | + if (quantity > 1) { |
| 14 | + setQuantity(quantity - 1) |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + const increaseQuantity = () => { |
| 19 | + setQuantity(quantity + 1) |
| 20 | + } |
| 21 | + |
| 22 | + const addToCart = () => { |
| 23 | + addItem(product, { count: quantity }) |
| 24 | + setQuantity(1) |
| 25 | + } |
| 26 | + |
| 27 | + return ( |
| 28 | + <article className="flex flex-col gap-3 bg-white p-8 rounded-xl shadow-md text-center mb-6"> |
| 29 | + <div className="text-8xl cursor-default">{emoji}</div> |
| 30 | + <div className="text-lg">{name}</div> |
| 31 | + <div className="text-2xl font-semibold mt-auto"> |
| 32 | + {formatCurrencyString({ value: price, currency: 'GBP' })} |
| 33 | + </div> |
| 34 | + <div className="flex justify-around items-center mt-4 mb-2 "> |
| 35 | + <button |
| 36 | + onClick={decreaseQuantity} |
| 37 | + className="hover:text-emerald-500 hover:bg-emerald-50 w-8 h-8 rounded-full transition-colors duration-500" |
| 38 | + > |
| 39 | + - |
| 40 | + </button> |
| 41 | + <span className="w-10 text-center rounded-md mx-3">{quantity}</span> |
| 42 | + <button |
| 43 | + onClick={increaseQuantity} |
| 44 | + className="hover:text-emerald-500 hover:bg-emerald-50 w-8 h-8 rounded-full transition-colors duration-500" |
| 45 | + > |
| 46 | + + |
| 47 | + </button> |
| 48 | + </div> |
| 49 | + <button |
| 50 | + onClick={() => addToCart()} |
| 51 | + className="bg-emerald-50 hover:bg-emerald-500 hover:text-white transition-colors duration-500 text-emerald-500 rounded-md px-5 py-2" |
| 52 | + > |
| 53 | + Add to cart |
| 54 | + </button> |
| 55 | + </article> |
| 56 | + ) |
| 57 | +} |
0 commit comments