Skip to content
Commerce block

Slide-Over Cart Drawer

A basket panel with the dialog mechanics usually missing: focus trap, focus return, Escape to close and a background scroll lock.

256 lineslucide-reactAdded 8 Aug 2026Updated 11 Sept 2026
  • cart
  • drawer
  • slide over
  • dialog
  • focus trap

What's included

  • components/cart-drawer.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add cart-drawer

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/cart-drawer.tsx
'use client'

/**
 * <CartDrawer> — a slide-over basket.
 *
 * The dialog mechanics that are usually missing:
 *
 *  - Focus moves into the panel on open and returns to whatever opened it
 *    on close. Without the return, a keyboard user is dumped back at the
 *    top of the document every time they dismiss the drawer.
 *  - Focus is trapped while open — Tab from the last control wraps to the
 *    first rather than walking into the page behind.
 *  - Escape closes it, and the backdrop is a real button so the "click
 *    outside" gesture is reachable without a mouse.
 *  - Background scroll is locked, or the page behind scrolls under the
 *    panel on touch.
 *
 * `role="dialog"` with `aria-modal` tells assistive tech the rest of the
 * page is inert; the focus trap is what makes that claim true.
 */

import * as React from 'react'
import { X, ShoppingBag, ArrowRight } from 'lucide-react'

export interface DrawerLine {
  id: string
  name: string
  variant?: string
  price: number
  quantity: number
  swatch?: string
}

export interface CartDrawerProps {
  lines?: DrawerLine[]
  currency?: string
  locale?: string
  defaultOpen?: boolean
  /**
   * Render as a demo inside a larger page rather than as a real overlay.
   *
   * An open drawer legitimately owns the document: it locks background
   * scroll, traps Tab and listens for Escape. A *preview* of one owns
   * nothing — it is a card in a grid, and a card that sets
   * `body { overflow: hidden }` freezes the page it is sitting on. Since
   * this block previews itself open, that lock would otherwise fire on
   * mount and never be cleaned up.
   */
  embedded?: boolean
  className?: string
}

const DEFAULT_LINES: DrawerLine[] = [
  { id: '1', name: 'Merino Crew Sweater', variant: 'Stone · M', price: 8900, quantity: 1, swatch: 'from-stone-300 to-stone-500' },
  { id: '2', name: 'Cotton Oxford Shirt', variant: 'Sky · L', price: 6500, quantity: 2, swatch: 'from-sky-200 to-sky-400' },
]

function formatPrice(minor: number, currency = 'GBP', locale = 'en-GB'): string {
  return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(minor / 100)
}

export function CartDrawer({
  lines = DEFAULT_LINES,
  currency = 'GBP',
  locale = 'en-GB',
  defaultOpen = true,
  embedded = false,
  className = '',
}: CartDrawerProps) {
  const [open, setOpen] = React.useState(defaultOpen)

  const panelRef = React.useRef<HTMLDivElement>(null)
  const openerRef = React.useRef<HTMLButtonElement>(null)

  const itemCount = lines.reduce((n, l) => n + l.quantity, 0)
  const subtotal = lines.reduce((n, l) => n + l.price * l.quantity, 0)

  // Focus in on open, back to the opener on close, Escape to dismiss, and
  // Tab trapped inside the panel.
  React.useEffect(() => {
    // Embedded: no scroll lock, no focus trap, no document key handler.
    // Returning focus to the opener is skipped too — in a grid of previews
    // that would scroll the visitor's page to this card unprompted.
    if (embedded) return

    if (!open) {
      openerRef.current?.focus()
      return
    }

    const panel = panelRef.current
    const previous = document.activeElement as HTMLElement | null

    const focusables = () =>
      Array.from(
        panel?.querySelectorAll<HTMLElement>(
          'a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex="-1"])',
        ) ?? [],
      )

    focusables()[0]?.focus()

    function onKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        setOpen(false)
        return
      }
      if (event.key !== 'Tab') return

      const items = focusables()
      if (items.length === 0) return

      const first = items[0]
      const last = items[items.length - 1]

      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault()
        last.focus()
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault()
        first.focus()
      }
    }

    document.addEventListener('keydown', onKeyDown)

    // Lock background scroll, restoring whatever was there before rather
    // than assuming it was `visible`.
    const previousOverflow = document.body.style.overflow
    document.body.style.overflow = 'hidden'

    return () => {
      document.removeEventListener('keydown', onKeyDown)
      document.body.style.overflow = previousOverflow
      previous?.focus?.()
    }
  }, [open, embedded])

  return (
    <div className={`relative min-h-96 ${className}`}>
      <div className="flex items-center justify-center p-10">
        <button
          ref={openerRef}
          type="button"
          onClick={() => setOpen(true)}
          className="inline-flex items-center gap-2 rounded-xl border border-border/60 bg-background px-4 py-2.5 text-sm font-medium transition-colors hover:bg-muted"
        >
          <ShoppingBag aria-hidden className="h-4 w-4" />
          Open bag
          <span className="rounded-full bg-primary px-1.5 py-0.5 text-xs font-semibold text-primary-foreground">
            {itemCount}
          </span>
        </button>
      </div>

      {open ? (
        <>
          {/* A real button, so dismissing does not require a pointer. */}
          <button
            type="button"
            aria-label="Close bag"
            onClick={() => setOpen(false)}
            className="absolute inset-0 z-30 cursor-default bg-black/40 backdrop-blur-sm border border-transparent"
          />

          <div
            ref={panelRef}
            role="dialog"
            aria-modal="true"
            aria-label="Shopping bag"
            className="absolute inset-y-0 end-0 z-40 flex w-full max-w-sm flex-col border-s border-border/60 bg-card shadow-2xl"
          >
            <div className="flex items-center justify-between gap-3 border-b border-border/60 px-5 py-4">
              <h2 className="font-semibold tracking-tight">
                Your bag
                <span className="ms-2 text-sm font-normal text-muted-foreground">
                  ({itemCount})
                </span>
              </h2>
              <button
                type="button"
                onClick={() => setOpen(false)}
                aria-label="Close bag"
                className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
              >
                <X aria-hidden className="h-4 w-4" />
              </button>
            </div>

            <ul className="flex-1 divide-y divide-border/40 overflow-y-auto px-5">
              {lines.map((line) => (
                <li key={line.id} className="flex gap-3 py-4">
                  <div className="h-20 w-16 shrink-0 overflow-hidden rounded-lg border border-border/60 bg-muted">
                    <div
                      aria-hidden
                      className={`h-full w-full bg-gradient-to-br ${line.swatch ?? 'from-muted to-muted-foreground/20'}`}
                    />
                  </div>

                  <div className="min-w-0 flex-1">
                    <h3 data-stress-ignore className="truncate text-sm font-medium">{line.name}</h3>
                    {line.variant ? (
                      <p className="mt-0.5 break-words text-xs text-muted-foreground">{line.variant}</p>
                    ) : null}
                    <p className="mt-2 text-sm text-muted-foreground">
                      {line.quantity} × {formatPrice(line.price, currency, locale)}
                    </p>
                  </div>

                  <p className="shrink-0 text-sm font-semibold tabular-nums">
                    {formatPrice(line.price * line.quantity, currency, locale)}
                  </p>
                </li>
              ))}

              {lines.length === 0 ? (
                <li className="py-16 text-center text-sm text-muted-foreground">
                  Your bag is empty.
                </li>
              ) : null}
            </ul>

            <div className="border-t border-border/60 px-5 py-4">
              <div className="flex items-baseline justify-between gap-4">
                <span className="text-sm text-muted-foreground">Subtotal</span>
                <span className="text-lg font-bold tabular-nums">
                  {formatPrice(subtotal, currency, locale)}
                </span>
              </div>
              <p className="mt-0.5 text-xs text-muted-foreground">
                Delivery and taxes calculated at checkout.
              </p>

              <a
                href="/checkout"
                className="mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90"
              >
                Checkout
                <ArrowRight aria-hidden className="h-4 w-4 rtl:rotate-180" />
              </a>

              <button
                type="button"
                onClick={() => setOpen(false)}
                className="mt-2 w-full rounded-xl px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground"
              >
                Continue shopping
              </button>
            </div>
          </div>
        </>
      ) : null}
    </div>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/cart-drawer.tsx and import it where you need the section:

import { CartDrawer } from '@/components/cart-drawer'

Customize

4 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
linesDrawerLine[]DEFAULT_LINES
currencystring'GBP'
localestring'en-GB'
defaultOpenbooleantrue
embeddedRender as a demo inside a larger page rather than as a real overlay. An open drawer legitimately owns the document: it locks background scroll, traps Tab and listens for Escape. A *preview* of one owns nothing — it is a card in a grid, and a card that sets `body { overflow: hidden }` freezes the page it is sitting on. Since this block previews itself open, that lock would otherwise fire on mount and never be cleaned up.booleanfalse
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

cart-drawer.html
<!--
  Slide-Over Cart Drawer — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<div class="relative min-h-96 ">
  <div class="flex items-center justify-center p-10">
    <button type="button" class="inline-flex items-center gap-2 rounded-xl border border-border/60 bg-background px-4 py-2.5 text-sm font-medium transition-colors hover:bg-muted"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shopping-bag h-4 w-4" aria-hidden="true"><path d="M16 10a4 4 0 0 1-8 0"></path><path d="M3.103 6.034h17.794"></path><path d="M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"></path></svg>Open bag<span class="rounded-full bg-primary px-1.5 py-0.5 text-xs font-semibold text-primary-foreground">3</span></button>
  </div>
  <button type="button" aria-label="Close bag" class="absolute inset-0 z-30 cursor-default bg-black/40 backdrop-blur-sm border border-transparent"></button>
  <div role="dialog" aria-modal="true" aria-label="Shopping bag" class="absolute inset-y-0 end-0 z-40 flex w-full max-w-sm flex-col border-s border-border/60 bg-card shadow-2xl">
    <div class="flex items-center justify-between gap-3 border-b border-border/60 px-5 py-4">
      <h2 class="font-semibold tracking-tight">Your bag<span class="ms-2 text-sm font-normal text-muted-foreground">(3)</span></h2>
      <button type="button" aria-label="Close bag" class="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x h-4 w-4" aria-hidden="true">
          <path d="M18 6 6 18"></path>
          <path d="m6 6 12 12"></path>
        </svg>
      </button>
    </div>
    <ul class="flex-1 divide-y divide-border/40 overflow-y-auto px-5">
      <li class="flex gap-3 py-4">
        <div class="h-20 w-16 shrink-0 overflow-hidden rounded-lg border border-border/60 bg-muted">
          <div aria-hidden="true" class="h-full w-full bg-gradient-to-br from-stone-300 to-stone-500"></div>
        </div>
        <div class="min-w-0 flex-1">
          <h3 data-stress-ignore="true" class="truncate text-sm font-medium">Merino Crew Sweater</h3>
          <p class="mt-0.5 break-words text-xs text-muted-foreground">Stone · M</p>
          <p class="mt-2 text-sm text-muted-foreground">1 × £89.00</p>
        </div>
        <p class="shrink-0 text-sm font-semibold tabular-nums">£89.00</p>
      </li>
      <li class="flex gap-3 py-4">
        <div class="h-20 w-16 shrink-0 overflow-hidden rounded-lg border border-border/60 bg-muted">
          <div aria-hidden="true" class="h-full w-full bg-gradient-to-br from-sky-200 to-sky-400"></div>
        </div>
        <div class="min-w-0 flex-1">
          <h3 data-stress-ignore="true" class="truncate text-sm font-medium">Cotton Oxford Shirt</h3>
          <p class="mt-0.5 break-words text-xs text-muted-foreground">Sky · L</p>
          <p class="mt-2 text-sm text-muted-foreground">2 × £65.00</p>
        </div>
        <p class="shrink-0 text-sm font-semibold tabular-nums">£130.00</p>
      </li>
    </ul>
    <div class="border-t border-border/60 px-5 py-4">
      <div class="flex items-baseline justify-between gap-4">
        <span class="text-sm text-muted-foreground">Subtotal</span>
        <span class="text-lg font-bold tabular-nums">£219.00</span>
      </div>
      <p class="mt-0.5 text-xs text-muted-foreground">Delivery and taxes calculated at checkout.</p>
      <a href="/checkout" class="mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90">Checkout<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-right h-4 w-4 rtl:rotate-180" aria-hidden="true"><path d="M5 12h14"></path><path d="m12 5 7 7-7 7"></path></svg></a>
      <button type="button" class="mt-2 w-full rounded-xl px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground">Continue shopping</button>
    </div>
  </div>
</div>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

Used in these pages

Want the whole screen instead of this one section? Open a page and copy it entire.

8 more blocks in Cart & Checkout

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Cart & Checkout

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Cart & Checkout blocks

View category
Open the full page for this block

Editable Cart Lines

Quantity steppers and remove-with-undo, with every total derived rather than stored so the basket can never disagree with itself.

Cart & Checkout199 lines1 dep
Open the full page for this block

Checkout Address & Payment

The full autocomplete token set that lets a browser fill eight fields in one tap, plus address labels that follow the selected country.

Cart & Checkout259 lines1 dep
Open the full page for this block

Order Summary With Promo

Subtotal, discount, delivery and tax all derived from the lines, with the free-delivery nudge driven by the same threshold as the charge.

Cart & Checkout228 lines1 dep
Open the full page for this block

Express Payment Row

The wallet buttons above the form, and what they do to it: the address a wallet returns is shown and stays editable, and the row disappears entirely when no wallet is actually available.

Cart & Checkout258 lines1 dep
Open the full page for this block

Gift Options Form

The gifting step, placed in the cart where it is a choice rather than at checkout where it is friction.

Cart & Checkout177 linesNo deps
Open the full page for this block

Gift Card Purchase

The only checkout where the buyer is not the recipient - live preview, a send date with a stated timezone, and the confirm-the-address field that prevents the expensive typo.

Cart & Checkout361 lines1 dep
Open the full page for this block

Guest Checkout

Guest as the default and the whole form, with a real autocomplete token on every field and the account offer moved to the end, where it costs one checkbox.

Cart & Checkout396 lines1 dep
Open the full page for this block

Discount Offer Modal

The offer popup with four rules applied: triggered by intent, a decline button of equal weight, a dismissal that is remembered, and the terms on its face.

Cart & Checkout214 lines1 dep