# Pricing Switcher
*URL: https://www.grettech.com/components/pricing-switcher*

Pricing plans with a monthly/yearly switch, prices that roll like an odometer, a highlighted plan and stacked feature lists.

- Prices roll digit by digit when billing changes, server-rendered
- Accessible monthly/yearly switch with arrow-key support
- "Everything in Starter, plus" feature lists
- Highlighted popular plan, any currency and locale

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/pricing-switcher
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/pricing-switcher-demo`

**Dependencies:** npm: clsx, tailwind-merge, lucide-react; shadcn/ui: button

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge lucide-react
npx shadcn@latest add button
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/pricing-switcher.tsx`
```tsx
"use client"

import { buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { Check } from "lucide-react"
import * as React from "react"

export type Billing = "monthly" | "yearly"

export interface PricingPlan {
  id: string
  name: string
  description?: string
  /** Price per month, and the total for a year */
  price: { monthly: number; yearly: number }
  features: string[]
  /** Shown above the features, e.g. "Everything in Starter, plus" */
  featuresIntro?: string
  cta: { label: string; href: string }
  /** Highlights the plan and shows the badge */
  popular?: boolean
}

export interface PricingSwitcherProps extends React.HTMLAttributes<HTMLDivElement> {
  plans: PricingPlan[]
  /** ISO 4217 code used to format prices */
  currency?: string
  locale?: string
  defaultBilling?: Billing
  /** Controlled billing period */
  billing?: Billing
  onBillingChange?: (billing: Billing) => void
  /** Shown next to the yearly option, e.g. "Save 20%" */
  yearlyNote?: string
  popularBadge?: string
  /** Component used for the plan links, e.g. next/link's Link */
  linkAs?: React.ElementType
}

/**
 * One digit as a vertical strip of 0–9, moved with a CSS transform. The
 * server renders the right digit in place, so prices never wait for JS.
 */
function RollingDigit({ digit }: { digit: number }) {
  return (
    <span className="relative inline-block h-[1em] overflow-hidden leading-none">
      <span className="invisible">0</span>
      <span
        aria-hidden="true"
        className="absolute inset-x-0 top-0 flex flex-col transition-transform duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none"
        style={{ transform: `translateY(-${digit * 10}%)` }}
      >
        {Array.from({ length: 10 }, (_, n) => (
          <span key={n} className="h-[1em]">
            {n}
          </span>
        ))}
      </span>
    </span>
  )
}

function RollingPrice({ text }: { text: string }) {
  const chars = [...text]
  return (
    <span className="inline-flex tabular-nums">
      {/* Screen readers get the plain price */}
      <span className="sr-only">{text}</span>
      <span aria-hidden="true" className="inline-flex">
        {chars.map((char, i) => {
          // Keyed from the right so units stay units when the length changes
          const key = chars.length - i
          return /\d/.test(char) ? (
            <RollingDigit key={key} digit={Number(char)} />
          ) : (
            <span key={key} className="leading-none">
              {char}
            </span>
          )
        })}
      </span>
    </span>
  )
}

export const PricingSwitcher = React.forwardRef<
  HTMLDivElement,
  PricingSwitcherProps
>(
  (
    {
      plans,
      currency = "USD",
      locale = "en-US",
      defaultBilling = "monthly",
      billing: controlledBilling,
      onBillingChange,
      yearlyNote = "Save 20%",
      popularBadge = "Most popular",
      linkAs: LinkTag = "a",
      className,
      ...props
    },
    ref
  ) => {
    const [internalBilling, setInternalBilling] = React.useState(defaultBilling)
    const billing = controlledBilling ?? internalBilling
    const setBilling = (next: Billing) => {
      setInternalBilling(next)
      onBillingChange?.(next)
    }

    const format = React.useMemo(
      () =>
        new Intl.NumberFormat(locale, {
          style: "currency",
          currency,
          maximumFractionDigits: 0,
        }),
      [locale, currency]
    )

    const options: { value: Billing; label: string }[] = [
      { value: "monthly", label: "Monthly" },
      { value: "yearly", label: "Yearly" },
    ]

    // Arrow keys move between the two options, like native radios
    const onKeyDown = (e: React.KeyboardEvent) => {
      if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(e.key))
        return
      e.preventDefault()
      const next = billing === "monthly" ? "yearly" : "monthly"
      setBilling(next)
      const target = e.currentTarget.querySelector<HTMLElement>(
        `[data-value="${next}"]`
      )
      target?.focus()
    }

    return (
      <div
        ref={ref}
        className={cn("flex w-full flex-col items-center gap-8", className)}
        {...props}
      >
        <div
          role="radiogroup"
          aria-label="Billing period"
          onKeyDown={onKeyDown}
          className="relative inline-flex rounded-full border bg-muted p-1 text-sm"
        >
          {/* Sliding thumb behind the active option */}
          <span
            aria-hidden="true"
            className={cn(
              "absolute inset-y-1 left-1 w-[calc(50%-0.25rem)] rounded-full bg-background shadow-sm transition-transform duration-300 ease-out motion-reduce:transition-none",
              billing === "yearly" && "translate-x-full"
            )}
          />
          {options.map((option) => {
            const active = billing === option.value
            return (
              <button
                key={option.value}
                type="button"
                role="radio"
                aria-checked={active}
                tabIndex={active ? 0 : -1}
                data-value={option.value}
                onClick={() => setBilling(option.value)}
                className={cn(
                  "relative z-10 inline-flex min-w-28 items-center justify-center gap-1.5 rounded-full px-4 py-1.5 font-medium transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
                  active ? "text-foreground" : "text-muted-foreground"
                )}
              >
                {option.label}
                {option.value === "yearly" && yearlyNote && (
                  <span className="rounded-full bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-semibold text-emerald-600 dark:text-emerald-400">
                    {yearlyNote}
                  </span>
                )}
              </button>
            )
          })}
        </div>

        <div
          className={cn(
            "grid w-full gap-4",
            plans.length >= 3 ? "md:grid-cols-3" : "md:grid-cols-2",
            plans.length >= 4 && "lg:grid-cols-4"
          )}
        >
          {plans.map((plan, p) => {
            const perMonth =
              billing === "yearly"
                ? Math.round(plan.price.yearly / 12)
                : plan.price.monthly
            return (
              <article
                key={`${plan.id}-${p}`}
                aria-labelledby={`${plan.id}-name`}
                className={cn(
                  "relative flex flex-col rounded-2xl border bg-card p-6 text-card-foreground",
                  plan.popular &&
                    "border-foreground/20 shadow-[0_20px_60px_-30px_rgba(0,0,0,0.35)] ring-1 ring-foreground/10 md:-my-2 md:py-8"
                )}
              >
                {plan.popular && popularBadge && (
                  <span className="absolute -top-3 left-6 rounded-full bg-foreground px-2.5 py-1 text-[11px] font-medium text-background">
                    {popularBadge}
                  </span>
                )}
                <h3 id={`${plan.id}-name`} className="text-base font-semibold">
                  {plan.name}
                </h3>
                {plan.description && (
                  <p className="mt-1 text-sm text-muted-foreground">
                    {plan.description}
                  </p>
                )}

                <div className="mt-6 flex items-end gap-1.5">
                  <span className="text-4xl font-semibold tracking-tight">
                    <RollingPrice text={format.format(perMonth)} />
                  </span>
                  <span className="pb-0.5 text-sm text-muted-foreground">
                    /month
                  </span>
                </div>
                <p className="mt-1 h-4 text-xs text-muted-foreground">
                  {billing === "yearly" &&
                    `Billed ${format.format(plan.price.yearly)} yearly`}
                </p>

                <LinkTag
                  href={plan.cta.href}
                  className={cn(
                    buttonVariants({
                      variant: plan.popular ? "default" : "outline",
                    }),
                    "mt-6 w-full"
                  )}
                >
                  {plan.cta.label}
                </LinkTag>

                <div className="mt-6 border-t pt-6">
                  {plan.featuresIntro && (
                    <p className="mb-3 text-xs font-medium text-muted-foreground">
                      {plan.featuresIntro}
                    </p>
                  )}
                  <ul className="space-y-2.5 text-sm">
                    {plan.features.map((feature, f) => (
                      <li key={`${feature}-${f}`} className="flex gap-2.5">
                        <Check
                          aria-hidden="true"
                          className="mt-0.5 size-4 shrink-0 text-emerald-500"
                        />
                        {feature}
                      </li>
                    ))}
                  </ul>
                </div>
              </article>
            )
          })}
        </div>
      </div>
    )
  }
)
PricingSwitcher.displayName = "PricingSwitcher"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `plans` | `PricingPlan[]` | - | Yes | The plans, in order. Two to four work best. |
| `plans.id` | `string` | - | Yes | Unique id, also used for element ids. |
| `plans.name` | `string` | - | Yes | Plan name. |
| `plans.description` | `string` | - | No | One line under the name. |
| `plans.price` | `{ monthly: number; yearly: number }` | - | Yes | Price per month, and the total for a year. Yearly billing shows the yearly total divided by 12. |
| `plans.price.monthly` | `number` | - | Yes | - |
| `plans.price.yearly` | `number` | - | Yes | - |
| `plans.features` | `string[]` | - | Yes | Feature list. |
| `plans.featuresIntro` | `string` | - | No | Shown above the features, e.g. "Everything in Starter, plus". |
| `plans.cta` | `{ label: string; href: string }` | - | Yes | The plan's button. |
| `plans.cta.label` | `string` | - | Yes | - |
| `plans.cta.href` | `string` | - | Yes | - |
| `plans.popular` | `boolean` | - | No | Highlights the plan and shows popularBadge. |
| `currency` | `string` | `"USD"` | No | ISO 4217 currency code for prices. |
| `locale` | `string` | `"en-US"` | No | Locale used to format prices. |
| `defaultBilling` | `"monthly" \| "yearly"` | `"monthly"` | No | Billing period shown first. |
| `billing` | `"monthly" \| "yearly"` | - | No | Controlled billing period. |
| `onBillingChange` | `(billing: Billing) => void` | - | No | Called when the visitor switches billing. |
| `yearlyNote` | `string` | `"Save 20%"` | No | Badge next to the yearly option. Pass an empty string to hide it. |
| `popularBadge` | `string` | `"Most popular"` | No | Badge on the popular plan. |
| `linkAs` | `React.ElementType` | `"a"` | No | Component used for links, e.g. next/link's Link. It receives href and className. |
| `className` | `string` | - | No | Extra classes for the root element. |
| `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | No | Any other attributes, passed to the root element. |

## Usage
```tsx
"use client"

import { PricingSwitcher, type PricingPlan } from "@/components/ui/pricing-switcher"

const PLANS: PricingPlan[] = [
  {
    id: "starter",
    name: "Starter",
    description: "For a polished one-page presence.",
    price: { monthly: 29, yearly: 276 },
    features: ["1-page website", "Custom domain", "Contact form", "SSL"],
    cta: { label: "Start with Starter", href: "#starter" },
  },
  {
    id: "growth",
    name: "Growth",
    description: "For businesses ready to scale.",
    price: { monthly: 79, yearly: 756 },
    featuresIntro: "Everything in Starter, plus",
    features: ["Up to 15 pages", "CMS for your team", "SEO setup", "Analytics"],
    cta: { label: "Choose Growth", href: "#growth" },
    popular: true,
  },
  {
    id: "scale",
    name: "Scale",
    description: "For products with real traffic.",
    price: { monthly: 199, yearly: 1908 },
    featuresIntro: "Everything in Growth, plus",
    features: [
      "Unlimited pages",
      "E-commerce",
      "Priority support",
      "Uptime SLA",
    ],
    cta: { label: "Talk to us", href: "#scale" },
  },
]

export default function PricingSwitcherDemo() {
  return (
    <div className="w-full px-4 py-10">
      <PricingSwitcher plans={PLANS} />
    </div>
  )
}

```
