Build a Cart Drawer
Slide-out cart with real-time updates.
Updated
On this page
Build a Cart Drawer
A sliding cart drawer that opens when items are added.
"use client"
import { useState, useEffect } from "react"
import dash from "@/lib/dash"
export function CartDrawer({ isOpen, onClose }) {
const [cart, setCart] = useState({ items: [], subtotal: "0.00" })
useEffect(() => {
if (isOpen) refreshCart()
}, [isOpen])
async function refreshCart() {
try {
const data = await dash.cart.get()
setCart(data)
} catch {}
}
async function updateQty(sizeId, qty) {
await dash.cart.update(sizeId, qty)
refreshCart()
}
async function removeItem(sizeId) {
await dash.cart.remove(sizeId)
refreshCart()
}
return (
<div className={`fixed right-0 top-0 h-full w-96 bg-gray-900 transform transition-transform
${isOpen ? "translate-x-0" : "translate-x-full"}`}>
<div className="p-6">
<div className="flex justify-between">
<h2 className="text-xl font-bold">Cart</h2>
<button onClick={onClose}>×</button>
</div>
{cart.items.length === 0 ? (
<p className="mt-8 text-center text-gray-400">Your cart is empty</p>
) : (
<>
{cart.items.map(item => (
<div key={item.size_id} className="flex gap-3 py-4 border-b border-gray-800">
<img src={item.product_image} alt="" className="w-16 h-16 rounded" />
<div className="flex-1">
<p className="font-medium">{item.product_name}</p>
<p className="text-sm text-gray-400">{item.size_label}</p>
<div className="flex items-center gap-2 mt-1">
<button onClick={() => updateQty(item.size_id, item.quantity - 1)}>-</button>
<span>{item.quantity}</span>
<button onClick={() => updateQty(item.size_id, item.quantity + 1)}>+</button>
</div>
</div>
<div className="text-right">
<p>${item.subtotal}</p>
<button onClick={() => removeItem(item.size_id)} className="text-red-400 text-sm">Remove</button>
</div>
</div>
))}
<div className="mt-4 pt-4 border-t border-gray-800">
<div className="flex justify-between text-lg font-bold">
<span>Subtotal</span><span>${cart.subtotal}</span>
</div>
<a href="/checkout" className="block w-full mt-4 bg-blue-600 text-center py-3 rounded">
Checkout
</a>
</div>
</>
)}
</div>
</div>
)
}