Skip to content
Browse documentation

Monthly or yearly: the thumb slides with a little give, and every price on the page rolls to its new amount.

Used forPricing pagesIn-app upgrade screensExtra periodsCheckout and upgrade dialogs

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/pricing-toggle.json

Registered the namespace? Then it’s shadcn add @hairline/pricing-toggle. Set it up

Templates

Need the whole page?

63 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

All 63 templates

Where it’s used

  • Pricing pages

    A Monthly and Yearly switch that drives every plan on the page.

  • In-app upgrade screens

    Let people compare billing periods when they change plan.

  • Extra periods

    Add Quarterly or Lifetime beside Monthly and Yearly.

  • Checkout and upgrade dialogs

    A billing choice that updates the total beside it.

What it handles for you

The billing switch is the one control every pricing page has, and usually the dullest. This one also rolls every price on the page to its new amount.

Instead of wiring upa billing switchprice formattinga “Save 20%” badgeprice change animationa billing note
  1. A thumb with a little give

    It slides and resizes to the chosen option, and the labels trade colour.

  2. A badge that lights up

    “Save 20%” sits inside Yearly and fills with your brand colour when Yearly is chosen.

  3. Every price rolls

    Each Price on the page rolls digit by digit to its new amount.

  4. A billing note that follows

    The line under the price, such as “$276 billed yearly”, slides in from the direction you switched.

  5. Any number of periods

    Pass your own options, for example add Lifetime.

  6. A real radio group

    Arrow keys move between periods. Prices are real text for screen readers.

Overview

The billing switch is the one control every pricing page has, and usually the dullest. Here the thumb slides and resizes to the chosen option with a little give at the end, and the labels trade colour. "Save 20%" sits inside Yearly and lights up in your brand colour when it’s chosen. Every Price on the page rolls digit by digit to its new amount, and the billing line underneath slides in from the direction you switched.

States

monthly
The thumb sits on Monthly; Yearly shows its badge in a soft tint as an incentive.
yearly
The thumb slides and widens over Yearly and its badge, and the badge fills with your brand colour.
prices
Each Price rolls to the new amount; the note ("$276 billed yearly") slides in from the toggle’s direction.

Usage

usage.tsx
import { Price, PricingToggle } from "@/components/pricing-toggle";const [billing, setBilling] = useState("monthly");<PricingToggle value={billing} onValueChange={setBilling} /><Price amount={billing === "yearly" ? 23 : 29} note={billing === "yearly" ? "$276 billed yearly" : "Billed monthly"} />

Works with

In a pricing section

One toggle drives every plan column; each Price rolls on its own.

example.tsx
"use client";import { useState } from "react";import { Price, PricingToggle } from "@/components/pricing-toggle";const plans = [  { name: "Starter", monthly: 12, yearly: 9 },  { name: "Pro", monthly: 29, yearly: 23 },  { name: "Team", monthly: 79, yearly: 63 },];export function Pricing() {  const [billing, setBilling] = useState("monthly");  const yearly = billing === "yearly";  return (    <section className="flex flex-col items-center gap-8">      <PricingToggle value={billing} onValueChange={setBilling} />      <div className="grid w-full gap-px overflow-hidden rounded-3xl border sm:grid-cols-3">        {plans.map((plan) => (          <div key={plan.name} className="bg-background p-6">            <h3 className="text-sm font-medium">{plan.name}</h3>            <Price              amount={yearly ? plan.yearly : plan.monthly}              direction={yearly ? 1 : -1}              note={yearly ? `$${plan.yearly * 12} billed yearly` : "Billed monthly"}            />          </div>        ))}      </div>    </section>  );}

Props

value / onValueChange
string / (value) => void
The chosen billing period.
options= Monthly, Yearly “Save 20%”
{ value; label; badge? }[]
Any number of periods, e.g. add Lifetime.
Price: amount / currency / period= — / "USD" / "/mo"
number / string / string
The figure that rolls, its currency, and the period after it (hidden at 0).
Price: locales
string | string[]
Format the price in this locale on the server and in the browser. Without it, a server render shows en-US and switches to the visitor’s locale after hydration ("$29" can become "US$29" in en-GB).
Price: note / direction
string / 1 | -1
The line under the price, sliding in from the way the toggle moved.
Price: numberClassName
string
Size and weight of the figure.

Accessibility and motion

  • The toggle is a real radio group: arrow keys move between periods, and only the chosen one is in the tab order.
  • Prices are real text for screen readers; the rolling digits are decoration on top.
  • Installs Number roll alongside it.
  • Price hydrates cleanly when server-rendered: without locales it formats in en-US until hydration, then in the visitor’s locale, swapped in place. The note is your own text, so if you write amounts in it, pass the same locales to Price to keep them alike.
  • With reduced motion, the thumb jumps and prices change in place.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll.

Source

components/pricing-toggle.tsx
"use client";import * as React from "react";import { NumberRoll } from "./number-roll";/* ───────────────────────────────────────────────────────── * PRICING TOGGLE: monthly or yearly, and every price rolls * *   toggle   the thumb slides and resizes to the chosen option *            with a little give; the labels trade colour *   badge    "Save 20%" sits inside Yearly and lights up in *            your brand colour when it's chosen *   prices   Price rolls each figure to its new amount, and the *            billing line crossfades in the direction you went * * PricingToggle is the control; Price is the number. Use them * together across your plan columns. * ───────────────────────────────────────────────────────── */export interface BillingOption {  value: string;  label: string;  /** e.g. "Save 20%". */  badge?: string;}export interface PricingToggleProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> {  value: string;  onValueChange: (value: string) => void;  options?: BillingOption[];  label?: string;  size?: "default" | "sm";}export interface PriceProps extends React.HTMLAttributes<HTMLDivElement> {  amount: number;  currency?: string;  /** Format in this locale everywhere. Without it, a server render and hydration use en-US and the visitor's locale takes over after mount. */  locales?: string | string[];  /** e.g. "/mo"; hidden for free plans. */  period?: string;  /** A line under the price, e.g. "$288 billed yearly". */  note?: string;  /** Which way the toggle moved (1 or -1), so the note slides with it. */  direction?: number;  /** Classes for the figure, e.g. its size. */  numberClassName?: string;}const BILLING: BillingOption[] = [  { value: "monthly", label: "Monthly" },  { value: "yearly", label: "Yearly", badge: "Save 20%" },];// A little give at the end of the slide, so the thumb feels like it was thrown, not placed.const THROW = "cubic-bezier(0.34,1.36,0.64,1)";const EASE = "cubic-bezier(0.23,1,0.32,1)";const FOCUS = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40";const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => {  const query = window.matchMedia(reducedQuery);  query.addEventListener("change", onChange);  return () => query.removeEventListener("change", onChange);};const useReducedMotion = () =>  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);export function PricingToggle({  value,  onValueChange,  options = BILLING,  label = "Billing period",  size = "default",  className = "",  ...props}: PricingToggleProps) {  const reduced = useReducedMotion();  const refs = React.useRef<(HTMLButtonElement | null)[]>([]);  const [thumb, setThumb] = React.useState({ left: 0, width: 0, ready: false });  const active = Math.max(0, options.findIndex((o) => o.value === value));  React.useLayoutEffect(() => {    const measure = () => {      const el = refs.current[active];      if (!el) return;      const left = el.offsetLeft;      const width = el.offsetWidth;      setThumb((t) => (t.left === left && t.width === width ? t : { left, width, ready: t.width > 0 }));    };    measure();    const observer = new ResizeObserver(measure);    refs.current.forEach((el) => el && observer.observe(el));    return () => observer.disconnect();  }, [active, options]);  const onKeyDown = (e: React.KeyboardEvent) => {    if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;    e.preventDefault();    const next = (active + (e.key === "ArrowRight" ? 1 : -1) + options.length) % options.length;    onValueChange(options[next].value);    refs.current[next]?.focus();  };  const isSm = size === "sm";  return (    <div      role="radiogroup"      aria-label={label}      onKeyDown={onKeyDown}      className={`relative inline-flex items-center rounded-full border border-border bg-background ${        isSm ? "p-0.5" : "p-0.5 sm:p-1"      } ${className}`}      {...props}    >      <span        aria-hidden="true"        className={`absolute left-0 rounded-full bg-[color-mix(in_oklab,var(--foreground)_8%,var(--background))] ${          isSm ? "inset-y-0.5" : "inset-y-0.5 sm:inset-y-1"        }`}        style={{          width: thumb.width,          transform: `translateX(${thumb.left}px)`,          transition: thumb.ready && !reduced ? `transform 520ms ${THROW}, width 420ms ${EASE}` : "none",        }}      />      {options.map((option, i) => {        const selected = i === active;        return (          <button            key={option.value}            ref={(el) => {              refs.current[i] = el;            }}            type="button"            role="radio"            aria-checked={selected}            tabIndex={selected ? 0 : -1}            onClick={() => onValueChange(option.value)}            className={`cursor-pointer relative flex items-center rounded-full font-medium transition-colors duration-300 ${FOCUS} ${              isSm                ? "h-7 gap-1.5 px-2.5 text-[12px]"                : "h-7 gap-1.5 px-2.5 text-[12px] sm:h-8 sm:gap-2 sm:px-3.5 sm:text-[13px]"            } ${              selected ? "text-foreground" : "text-muted-foreground hover:text-foreground"            }`}          >            {option.label}            {option.badge && (              <span                className={`rounded-full font-medium transition-[background-color,color] duration-300 ${                  isSm ? "px-1.5 py-0.5 text-[10px]" : "px-1.5 py-0.5 text-[10px] sm:py-px sm:text-[11px]"                } ${                  selected ? "bg-primary text-primary-foreground" : "bg-primary/10 text-primary"                }`}              >                {option.badge}              </span>            )}          </button>        );      })}    </div>  );}export function Price({  amount,  currency = "USD",  locales,  period = "/mo",  note,  direction = 1,  numberClassName = "text-[40px] font-medium leading-[1.15] tracking-[-0.03em] text-foreground",  className = "",  ...props}: PriceProps) {  const format = React.useMemo<Intl.NumberFormatOptions>(    () => ({ style: "currency", currency, maximumFractionDigits: amount % 1 ? 2 : 0, minimumFractionDigits: amount % 1 ? 2 : 0 }),    [currency, amount]  );  return (    <div className={className} {...props}>      <div className="flex items-baseline gap-1">        <NumberRoll value={amount} format={format} locales={locales} className={numberClassName} />        {amount > 0 && period && <span className="text-[14px] text-muted-foreground">{period}</span>}      </div>      {note !== undefined && (        <div className="relative mt-1 h-5 overflow-hidden text-[12.5px] text-muted-foreground">          <span            key={note}            className="absolute inset-0 truncate motion-safe:animate-[ui-note-in_380ms_cubic-bezier(0.23,1,0.32,1)_both]"            style={{ "--ui-from": `${direction > 0 ? 100 : -100}%` } as React.CSSProperties}          >            {note}          </span>        </div>      )}    </div>  );}

Registry item: /r/pricing-toggle.json