# Product Card

> The product tile for collection grids and rails, with swatches, quick add and a wishlist heart. Handles sold-out sizes, price ranges and failed adds.

Canonical: https://hextaui.com/blocks/product-card
Last updated: 2026-10-29

## Overview

Product Card is the tile you put in a collection grid, search results or a recommendations rail. It takes a Product, the same model Variant Picker uses, and shows one card per product, never one per color. The whole card is a single link on the title, while the heart, swatches and quick add stay separate buttons on top of it.

Colors show as a row of small swatches, all of them reachable. On a narrow card the row scrolls sideways with the last swatch cut off and the edge faded, so shoppers can tell there are more. Hovering a swatch previews that color’s photo after a short pause and preloads it, so the crossfade never shows a blank frame. Clicking it picks the color: the price, badges and stock follow it, and the link opens the product page with ?color= set. On a mouse, hovering the card crossfades to a second photo.

Quick add fits the product. A product with one variant gets an Add to bag button that keeps its width while it changes to a spinner, Added or Couldn’t add. A product with sizes shows a row of size buttons that slides up over the photo on hover or keyboard focus, with sold-out sizes crossed out. On touch screens a + button opens a bottom sheet with Variant Picker instead. A sold-out product hides quick add, shows a Sold out badge and a Notify me link.

Badges come from the data: Sale −20%, Only 3 left, Pre-order and Sold out, plus your own such as New, two at most. The wishlist heart saves optimistically, pops once when saved, and rolls back with a message if your callback throws. ProductGrid lays cards out in 2, 3 or 4 columns and animates between them, and ProductCardSkeleton matches the card’s shape exactly for loading states.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/product-card
```

## Usage

### A Shopify collection

Map each Storefront API product once and pass it in. onQuickAdd gets the chosen variant, so adding to the cart is one fetch. If your route throws, its message shows on the card where the shopper clicked.

```tsx
import { fromShopify } from "../variant-picker/shopify"
import { ProductCard, ProductGrid } from "@/components/blocks/product-card/product-card"

type ShopifyProduct = Parameters<typeof fromShopify>[0] & {
  rating: { value: string } | null
  ratingCount: { value: string } | null
}

type Collection = {
  title: string
  products: { nodes: ShopifyProduct[] }
}

async function addToCart(merchandiseId: string) {
  const response = await fetch("/api/cart/lines", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ merchandiseId, quantity: 1 }),
  })
  if (!response.ok) {
    const { message } = await response.json()
    throw new Error(message ?? "Couldn’t add this to your bag. Try again.")
  }
}

export function CollectionGrid({ collection }: { collection: Collection }) {
  return (
    <ProductGrid columns={4} aria-label={collection.title}>
      {collection.products.nodes.map((node, index) => {
        const product = fromShopify(node)
        const count = Number(node.ratingCount?.value ?? 0)
        return (
          <ProductCard
            key={product.id}
            product={product}
            href={`/products/${node.handle}`}
            priority={index < 4}
            rating={count > 0 ? { value: Number(JSON.parse(node.rating?.value ?? "{}").value ?? 0), count } : null}
            onQuickAdd={(variant) => addToCart(variant.id)}
          />
        )
      })}
    </ProductGrid>
  )
}
```

### A recommendations rail

Put compact cards in a horizontally scrolling list for “You may also like” or “Complete the look”. Each card keeps its own swatches and quick add, so the rail needs no extra state.

```tsx
import type { Product, ProductVariant } from "../variant-picker/product"
import { ProductCard } from "@/components/blocks/product-card/product-card"

type RecommendationsProps = {
  title: string
  products: Product[]
  addToBag: (variantId: string) => Promise<void>
}

export function Recommendations({ title, products, addToBag }: RecommendationsProps) {
  if (products.length === 0) return null
  return (
    <section aria-labelledby="recommendations" className="flex flex-col gap-4">
      <h2 id="recommendations" className="text-lg font-medium">
        {title}
      </h2>
      <ul
        role="list"
        className="-mx-4 flex snap-x snap-mandatory gap-3 overflow-x-auto px-4 pb-2"
      >
        {products.map((product) => (
          <li key={product.id} className="w-44 shrink-0 snap-start sm:w-56">
            <ProductCard
              product={product}
              size="sm"
              headingLevel={3}
              onQuickAdd={(variant: ProductVariant) => addToBag(variant.id)}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}
```

### A wishlist saved to your API

The heart fills right away and rolls back if the request fails. Signed-out shoppers save to localStorage, so saving never needs an account, and signed-in shoppers save to your API.

```tsx
"use client"

import * as React from "react"

import type { Product } from "../variant-picker/product"
import { ProductCard, ProductGrid } from "@/components/blocks/product-card/product-card"

const storageKey = "wishlist"

function readLocal(): string[] {
  try {
    return JSON.parse(localStorage.getItem(storageKey) ?? "[]")
  } catch {
    return []
  }
}

export function WishlistGrid({
  products,
  signedIn,
}: {
  products: Product[]
  signedIn: boolean
}) {
  const [saved, setSaved] = React.useState<string[]>([])

  React.useEffect(() => {
    if (!signedIn) {
      setSaved(readLocal())
      return
    }
    fetch("/api/wishlist")
      .then((response) => response.json())
      .then((data: { productIds: string[] }) => setSaved(data.productIds))
  }, [signedIn])

  const change = async (next: boolean, product: Product) => {
    const ids = next
      ? [...saved, product.id]
      : saved.filter((id) => id !== product.id)
    if (signedIn) {
      const response = await fetch(`/api/wishlist/${encodeURIComponent(product.id)}`, {
        method: next ? "PUT" : "DELETE",
      })
      if (!response.ok) throw new Error("Couldn’t update your wishlist. Try again.")
    } else {
      localStorage.setItem(storageKey, JSON.stringify(ids))
    }
    setSaved(ids)
  }

  return (
    <ProductGrid columns={3}>
      {products.map((product) => (
        <ProductCard
          key={product.id}
          product={product}
          wishlisted={saved.includes(product.id)}
          onWishlistChange={change}
        />
      ))}
    </ProductGrid>
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `ProductCard` | Photo, badges, wishlist heart, quick add, swatches, vendor, title, price and rating. |
| `ProductGrid` | A responsive list of cards with 2, 3 or 4 columns and a loading state. |
| `ProductCardSkeleton` | A loading placeholder with the card’s exact geometry. |
| `getAutoBadges, getCardPrice, getQuickAddMode, getSizeChips` | The pure helpers behind the card, usable on the server. |

## API reference

### ProductCard

Also takes article props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `product` | `Product` | – | The product with its options, variants and images. |
| `href` | `string \| (color) => string` | `"/products/{handle}"` | Where the card links. A string gets ?color= added once the shopper picks a color. |
| `linkRender` | `ReactElement<a>` | – | Render the title link with your router’s Link, such as <Link prefetch />. |
| `selectedColor` | `string` | – | The chosen swatch value when controlled. The swatch option is the one with swatches. |
| `defaultSelectedColor` | `string` | – | The starting swatch value. Defaults to the first color in stock. |
| `onSelectedColorChange` | `(color: string) => void` | – | Called when the shopper picks a color. |
| `badges` | `(string \| { id; label; tone? })[]` | – | Your own badges, shown after the automatic ones. |
| `autoBadges` | `boolean` | `true` | Show Sale, Low stock, Pre-order and Sold out from the data. |
| `maxBadges` | `number` | `2` | The most badges shown at once. |
| `rating` | `{ value: number; count: number } \| null` | – | Shows stars with “4.8 (126)”. Hidden when count is 0. |
| `wishlisted` | `boolean` | – | Whether the product is saved, when controlled. |
| `defaultWishlisted` | `boolean` | `false` | The starting saved state when uncontrolled. |
| `onWishlistChange` | `(wishlisted, product) => void \| Promise<void>` | – | Shows the heart. The heart changes right away and rolls back if this throws or rejects. |
| `onQuickAdd` | `(variant, product) => void \| Promise<void>` | – | Shows quick add. The card shows pending, added and error states from the returned promise. |
| `notifyHref` | `string` | – | Where Notify me links for a sold-out product. Defaults to the product link with ?notify=1. |
| `size` | `"sm" \| "default"` | – | Card density. Inside ProductGrid it follows the column count. |
| `priority` | `boolean` | `false` | Load the photo eagerly with high priority, for cards above the fold. |
| `imageSizes` | `string` | – | The sizes attribute for the photo. |
| `headingLevel` | `2 \| 3 \| 4` | `3` | The heading level of the title. |
| `locale` | `Intl.LocalesArgument` | `"en-US"` | Locale for prices and counts. |
| `trailingZeros` | `boolean` | `false` | Show $48.00 instead of $48. |
| `labels` | `Partial<ProductCardLabels>` | – | Words for buttons, badges, swatch names and announcements. |

### ProductGrid

Also takes ul props. Each child is wrapped in a list item.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `columns` | `2 \| 3 \| 4` | `3` | Columns on wide screens. Phones show 1 column for 2 and 2 columns otherwise. |
| `size` | `"sm" \| "default"` | – | Card density. Defaults to sm at 4 columns. |
| `loading` | `boolean` | `false` | Show skeletons and set aria-busy. |
| `skeletonCount` | `number` | `8` | How many skeletons to show while loading. |
| `skeleton` | `ReactNode` | – | A custom skeleton for each loading cell. |

### ProductCardSkeleton

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `"sm" \| "default"` | – | Match the card density. |
| `swatches` | `boolean` | `true` | Include the swatch row. |
| `rating` | `boolean` | `false` | Include the rating line. |

## Keyboard

| Key | Action |
| --- | --- |
| `Tab` | Moves from the product link to the heart, the quick add buttons and each swatch. Focusing the card reveals the size row. |
| `Enter` | Opens the product page from the link, or adds the focused size. |
| `Space` | Toggles the heart, picks the focused swatch or adds the focused size. |
| `Escape` | Closes the quick add sheet and returns focus to the + button. |

## Accessibility

- The card is one link named by the product title, inside a heading. The heart, swatches and quick add are separate buttons layered above it, never nested inside the link.
- Swatches are named like “Sage, 3 of 5” and say when a color is sold out. The chosen one has aria-pressed. Sold-out sizes stay focusable with aria-disabled and are named “Twin, sold out”.
- The heart uses aria-pressed and the label “Save Ring Vase to wishlist”. A polite live region announces saves, removals and adds, such as “Added Washed Linen Duvet Cover, White / King, to your bag”, and failures are announced as alerts.
- Hover-only effects are limited to mouse pointers, and the size row also opens on keyboard focus. Motion is transform and opacity only, and reduced motion keeps only short fades.

## Built with

The free HextaUI components Product Card is made from. Each one installs on its own.

- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Sheet](https://hextaui.com/docs/sheet) - A panel that slides in from any edge, with swipe-to-dismiss, scroll lock and stacked nesting.
- [Skeleton](https://hextaui.com/docs/skeleton) - Placeholders that wait 150ms before showing, take the exact size of the content they wrap, and fade it in without moving anything.
- [Spinner](https://hextaui.com/docs/spinner) - A loading indicator with Apple-style ticks or a breathing ring that can wait before showing and stay long enough not to flicker.
- [Toast](https://hextaui.com/docs/toast) - Brief messages that stack neatly, expand on hover, swipe away, and turn a loading state into success or error in place.

## Code

6 files, added to components/blocks/product-card.
