Checkout summary
A checkout section with a payment method chooser beside an order summary. The summary lists line items with quantities, takes a discount code through your validator (sync or async, with checking, applied and invalid states), and works out subtotal, discount, shipping, tax after discount and total. Payment options are radio cards that can reveal details when selected, and the pay button shows processing and order-placed states. Stacks to one column on small screens.
Source
"use client";
import * as React from "react";
import { CircleCheck, LoaderCircle, Lock, TicketPercent, X, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
export interface OrderLine {
id: string;
name: string;
variant?: string;
/** Unit price. */
price: number;
quantity: number;
thumbnail?: React.ReactNode;
color?: string;
}
export interface Discount {
code: string;
/** percent: value is 0–100. amount: value is money. shipping: free shipping. */
type: "percent" | "amount" | "shipping";
value?: number;
}
export interface PaymentMethod {
id: string;
label: string;
description?: string;
icon?: LucideIcon;
/** Shown under the option while it is selected. */
details?: React.ReactNode;
}
export interface PlacedOrder {
paymentMethod: string;
discount: Discount | null;
subtotal: number;
total: number;
}
export interface CheckoutSummaryProps {
items: OrderLine[];
/** Shipping cost; 0 shows "Free". */
shipping?: number;
/** Tax rate applied after discounts, e.g. 0.08. */
taxRate?: number;
currency?: string;
locale?: string;
/** Checks a discount code. Return the discount, or null when it is not valid. May be async. */
validateCode?: (code: string) => Discount | null | Promise<Discount | null>;
paymentMethods: PaymentMethod[];
defaultPaymentMethod?: string;
/** Resolve to show the confirmation; return a string to show it as the order reference. */
onPlaceOrder?: (order: PlacedOrder) => void | string | Promise<void | string>;
className?: string;
}
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring";
export function CheckoutSummary({
items,
shipping = 0,
taxRate = 0,
currency = "USD",
locale,
validateCode,
paymentMethods,
defaultPaymentMethod,
onPlaceOrder,
className,
}: CheckoutSummaryProps) {
const id = React.useId();
const money = React.useMemo(() => new Intl.NumberFormat(locale, { style: "currency", currency }), [locale, currency]);
const [method, setMethod] = React.useState(defaultPaymentMethod ?? paymentMethods[0]?.id ?? "");
const [code, setCode] = React.useState("");
const [discount, setDiscount] = React.useState<Discount | null>(null);
const [codeState, setCodeState] = React.useState<"idle" | "checking" | "invalid">("idle");
const [orderState, setOrderState] = React.useState<"idle" | "placing" | "placed" | "failed">("idle");
const [reference, setReference] = React.useState<string | null>(null);
const codeInput = React.useRef<HTMLInputElement>(null);
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const off =
discount?.type === "percent" ? (subtotal * (discount.value ?? 0)) / 100 : discount?.type === "amount" ? Math.min(subtotal, discount.value ?? 0) : 0;
const shippingCost = discount?.type === "shipping" ? 0 : shipping;
const tax = Math.round((subtotal - off) * taxRate * 100) / 100;
const total = Math.max(0, subtotal - off + shippingCost + tax);
async function apply(event: React.FormEvent) {
event.preventDefault();
const value = code.trim().toUpperCase();
if (!value || !validateCode) return;
setCodeState("checking");
const result = await validateCode(value);
if (result) {
setDiscount(result);
setCode("");
setCodeState("idle");
} else {
setCodeState("invalid");
codeInput.current?.focus();
}
}
async function place() {
setOrderState("placing");
try {
const result = await onPlaceOrder?.({ paymentMethod: method, discount, subtotal, total });
setReference(typeof result === "string" ? result : null);
setOrderState("placed");
} catch {
setOrderState("failed");
}
}
const discountLabel =
discount?.type === "percent" ? `${discount.value}% off` : discount?.type === "amount" ? `${money.format(discount.value ?? 0)} off` : "Free shipping";
return (
<div className={cn("grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,25rem)] lg:gap-10", className)}>
<fieldset className="min-w-0" disabled={orderState === "placing" || orderState === "placed"}>
<legend className="mb-4 text-base font-semibold tracking-tight">Payment method</legend>
<div className="grid gap-3">
{paymentMethods.map((option) => {
const selected = option.id === method;
return (
<label
key={option.id}
className={cn(
"relative block cursor-pointer rounded-xl border bg-card p-4 text-card-foreground transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring",
selected ? "border-foreground/80 shadow-xs" : "hover:bg-accent/40",
)}
>
<span className="flex items-center gap-3">
<input
type="radio"
name={`${id}-payment`}
value={option.id}
checked={selected}
onChange={() => setMethod(option.id)}
className="size-4 shrink-0 accent-primary dark:[color-scheme:dark]"
/>
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">{option.label}</span>
{option.description && <span className="block text-xs text-muted-foreground">{option.description}</span>}
</span>
{option.icon && (
<span aria-hidden className="grid size-9 shrink-0 place-items-center rounded-lg border bg-background text-muted-foreground">
<option.icon className="size-[18px]" />
</span>
)}
</span>
{selected && option.details && <span className="mt-3 block border-t pt-3 pl-7 text-sm">{option.details}</span>}
</label>
);
})}
</div>
</fieldset>
<section aria-labelledby={`${id}-summary`} className="rounded-xl border bg-card text-card-foreground shadow-xs">
<div className="flex items-baseline justify-between border-b px-5 py-4">
<h2 id={`${id}-summary`} className="font-semibold tracking-tight">
Order summary
</h2>
<span className="text-xs text-muted-foreground tabular-nums">
{items.reduce((sum, item) => sum + item.quantity, 0)} items
</span>
</div>
<ul className="space-y-4 px-5 py-4">
{items.map((item) => (
<li key={item.id} className="flex items-center gap-3">
<span
className="relative grid size-14 shrink-0 place-items-center rounded-lg border"
style={{ background: item.color ? `color-mix(in oklab, ${item.color} 16%, var(--muted))` : undefined }}
>
{item.thumbnail ?? <span aria-hidden className="size-6 rounded-full" style={{ background: item.color || "var(--muted-foreground)" }} />}
{item.quantity > 1 && (
<span className="absolute -top-1.5 -right-1.5 grid size-5 place-items-center rounded-full bg-primary text-[10px] font-semibold text-primary-foreground tabular-nums">
{item.quantity}
<span className="sr-only"> pieces</span>
</span>
)}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{item.name}</span>
{item.variant && <span className="block truncate text-xs text-muted-foreground">{item.variant}</span>}
</span>
<span className="text-sm font-medium tabular-nums">{money.format(item.price * item.quantity)}</span>
</li>
))}
</ul>
{validateCode && (
<div className="border-t px-5 py-4">
{discount ? (
<div className="flex items-center justify-between gap-3">
<span className="inline-flex min-w-0 items-center gap-2 rounded-md bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-400">
<TicketPercent aria-hidden className="size-3.5 shrink-0" />
<span className="truncate font-mono">{discount.code}</span>
<span className="font-normal opacity-80">· {discountLabel}</span>
</span>
<button
type="button"
onClick={() => setDiscount(null)}
aria-label={`Remove code ${discount.code}`}
className={cn("grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground", focusRing)}
>
<X aria-hidden className="size-4" />
</button>
</div>
) : (
<form onSubmit={apply} noValidate>
<label htmlFor={`${id}-code`} className="sr-only">
Discount code
</label>
<div className="flex gap-2">
<input
ref={codeInput}
id={`${id}-code`}
value={code}
onChange={(event) => {
setCode(event.target.value);
if (codeState === "invalid") setCodeState("idle");
}}
placeholder="Discount code"
autoComplete="off"
spellCheck={false}
aria-invalid={codeState === "invalid"}
aria-describedby={`${id}-code-message`}
className="h-9 min-w-0 flex-1 rounded-md border border-input bg-background px-3 text-sm uppercase shadow-xs outline-none placeholder:text-muted-foreground placeholder:normal-case focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 aria-invalid:border-destructive aria-invalid:ring-destructive/20"
/>
<button
type="submit"
disabled={!code.trim() || codeState === "checking"}
className={cn("inline-flex h-9 min-w-20 items-center justify-center rounded-md border bg-background px-3 text-sm font-medium hover:bg-accent disabled:opacity-50", focusRing)}
>
{codeState === "checking" ? <LoaderCircle aria-label="Checking" className="size-4 motion-safe:animate-spin" /> : "Apply"}
</button>
</div>
<p id={`${id}-code-message`} aria-live="polite" className={cn("text-xs text-destructive", codeState === "invalid" && "mt-1.5")}>
{codeState === "invalid" ? "This code isn't valid." : ""}
</p>
</form>
)}
</div>
)}
<dl className="space-y-2 border-t px-5 py-4 text-sm">
<div className="flex justify-between">
<dt className="text-muted-foreground">Subtotal</dt>
<dd className="tabular-nums">{money.format(subtotal)}</dd>
</div>
{off > 0 && (
<div className="flex justify-between">
<dt className="text-muted-foreground">Discount</dt>
<dd className="text-emerald-700 tabular-nums dark:text-emerald-400">−{money.format(off)}</dd>
</div>
)}
<div className="flex justify-between">
<dt className="text-muted-foreground">Shipping</dt>
<dd className="tabular-nums">{shippingCost === 0 ? "Free" : money.format(shippingCost)}</dd>
</div>
{taxRate > 0 && (
<div className="flex justify-between">
<dt className="text-muted-foreground">Tax ({Math.round(taxRate * 1000) / 10}%)</dt>
<dd className="tabular-nums">{money.format(tax)}</dd>
</div>
)}
<div className="flex items-baseline justify-between border-t pt-3">
<dt className="font-medium">Total</dt>
<dd className="text-xl font-semibold tracking-tight tabular-nums">{money.format(total)}</dd>
</div>
</dl>
<div className="px-5 pb-5" aria-live="polite">
{orderState === "placed" ? (
<div className="flex items-center gap-3 rounded-lg bg-emerald-500/10 p-3 text-sm text-emerald-800 dark:text-emerald-300">
<CircleCheck aria-hidden className="size-5 shrink-0" />
<span>
<span className="block font-medium">Order placed</span>
{reference && <span className="block text-xs opacity-80">Reference {reference}</span>}
</span>
</div>
) : (
<>
<button
type="button"
onClick={place}
disabled={orderState === "placing" || !items.length || !method}
className={cn(
"inline-flex h-11 w-full items-center justify-center gap-2 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-70",
focusRing,
"focus-visible:ring-offset-2 focus-visible:ring-offset-card",
)}
>
{orderState === "placing" ? <LoaderCircle aria-hidden className="size-4 motion-safe:animate-spin" /> : <Lock aria-hidden className="size-4" />}
{orderState === "placing" ? "Processing…" : `Pay ${money.format(total)}`}
</button>
{orderState === "failed" && <p className="mt-2 text-center text-xs text-destructive">Payment failed. Try again.</p>}
</>
)}
</div>
</section>
</div>
);
}
