Monthly and Annual Billing Switch
A two option radio group, drawn as a segmented control with the annual saving written beside it, that reprices a grid of plans. Use on any page that sells two billing intervals.
How it differs. A two state interval choice built from native radios, not a toggle. Each plan pairs its monthly figure with a two row ledger of the yearly charge and the saving, so the sums reconcile.
Install
pnpm dlx shadcn@latest add @hazine/billing-switch-interval-radioAdds 1 file, 1 shadcn primitive (button), 2 Hazine items (@hazine/heading, @hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/blocks/billing-switch-interval-radio.tsx, 429 lines
"use client"
import * as React from "react"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Heading, nextHeadingLevel, type HeadingLevel } from "@/components/hazine/heading"
import { useControllableState } from "@/hooks/use-controllable-state"
export type BillingInterval = "monthly" | "annual"
export interface BillingPlan {
id: string
name: string
description: string
/** Price of one month when billed monthly. */
monthly: number
/** Price of one year when billed annually, charged once. */
annual: number
features: string[]
/** Verb first. The chosen interval is appended for paid plans. */
actionLabel: string
/** Checkout link per interval. */
href: Record<BillingInterval, string>
recommended?: boolean
}
export interface BillingSwitchIntervalRadioProps
extends Omit<React.ComponentProps<"section">, "title" | "defaultValue" | "onChange"> {
title?: string
plans?: BillingPlan[]
value?: BillingInterval
defaultValue?: BillingInterval
onValueChange?: (value: BillingInterval) => void
/** ISO 4217 code. */
currency?: string
locale?: string
/** Locks the interval choice. Pair it with `disabledReason`. */
disabled?: boolean
/** Sentence shown under the locked control. */
disabledReason?: string
/** Prices are on their way: figures become skeletons and the actions wait. */
loading?: boolean
/** Target of the sales link under the plans and of the empty state action. */
contactHref?: string
/** Marker on the plan flagged `recommended`. */
recommendedLabel?: string
headingLevel?: HeadingLevel
}
const DEFAULT_PLANS: BillingPlan[] = [
{
id: "hobby",
name: "Hobby",
description: "For a personal site or a side project.",
monthly: 0,
annual: 0,
features: ["10 monitors", "Checks every 5 minutes", "Email alerts"],
actionLabel: "Start on Hobby",
href: { monthly: "#hobby", annual: "#hobby" },
},
{
id: "team",
name: "Team",
description: "For a product team with an on-call rota.",
monthly: 30,
annual: 288,
features: [
"100 monitors",
"Checks every minute",
"On-call schedules and escalation",
"Status page on your own domain",
],
actionLabel: "Start Team",
href: { monthly: "#team-monthly", annual: "#team-annual" },
recommended: true,
},
{
id: "scale",
name: "Scale",
description: "For several products watched from several regions.",
monthly: 90,
annual: 864,
features: [
"500 monitors",
"Checks every 30 seconds",
"Probes in 12 regions",
"Single sign-on",
],
actionLabel: "Start Scale",
href: { monthly: "#scale-monthly", annual: "#scale-annual" },
},
]
const INTERVALS: { value: BillingInterval; label: string }[] = [
{ value: "monthly", label: "Monthly" },
{ value: "annual", label: "Annual" },
]
const SEGMENT_CLASS =
"group relative flex min-h-9 cursor-pointer items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-colors duration-100 hover:bg-muted/50 active:bg-muted has-[:checked]:bg-primary has-[:checked]:text-primary-foreground has-[:checked]:hover:bg-primary has-[:checked]:active:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-foreground has-[:disabled]:pointer-events-none has-[:disabled]:opacity-50"
const LINK_CLASS =
"inline-flex min-h-6 items-center font-medium text-foreground underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
const SKELETON_CLASS = "rounded-md bg-muted motion-safe:animate-pulse"
const cents = (amount: number) => Math.round(amount * 100) / 100
const yearlySaving = (plan: BillingPlan) => Math.max(0, cents(plan.monthly * 12 - plan.annual))
// The hairline grid shows its line colour wherever a row is not full, so the
// last row is padded for the two and the three column layout separately.
function fillerClass(index: number, count: number) {
const inTwoColumns = index < count % 2
const inThreeColumns = index < (3 - (count % 3)) % 3
return cn(
"hidden bg-background",
inTwoColumns ? "@2xl:block" : "@2xl:hidden",
inThreeColumns ? "@5xl:block" : "@5xl:hidden"
)
}
interface PlanCellProps {
plan: BillingPlan
interval: BillingInterval
money: Intl.NumberFormat
loading: boolean
recommendedLabel: string
headingLevel: HeadingLevel
}
function BillingSwitchIntervalRadioPlan({
plan,
interval,
money,
loading,
recommendedLabel,
headingLevel,
}: PlanCellProps) {
const annual = interval === "annual"
const saving = yearlySaving(plan)
const perMonth = annual ? plan.annual / 12 : plan.monthly
const perYear = annual ? plan.annual : plan.monthly * 12
const paid = plan.monthly > 0 || plan.annual > 0
const actionLabel = paid
? `${plan.actionLabel} ${annual ? "yearly" : "monthly"}`
: plan.actionLabel
const variant = plan.recommended ? "default" : "outline"
return (
<div className="flex h-full flex-col p-6">
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
<Heading level={headingLevel} className="min-w-0 text-lg font-semibold break-words">
{plan.name}
</Heading>
{plan.recommended && (
<span className="font-mono text-xs font-medium tracking-wider text-muted-foreground uppercase">
{recommendedLabel}
</span>
)}
</div>
<p className="mt-1 max-w-[40ch] text-sm text-pretty text-muted-foreground @5xl:min-h-10">{plan.description}</p>
{loading ? (
<div aria-hidden="true" className={cn("mt-6 h-10 w-24", SKELETON_CLASS)} />
) : (
<p
data-slot="billing-switch-interval-radio-price"
className="mt-6 flex flex-wrap items-baseline gap-1"
>
<span className="text-4xl font-semibold tracking-tight whitespace-nowrap tabular-nums">
{money.format(perMonth)}
</span>
<span aria-hidden="true" className="text-xs text-muted-foreground">
/mo
</span>
<span className="sr-only">per month</span>
</p>
)}
<dl className="mt-4 divide-y divide-border border-y border-border text-sm">
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted-foreground">
{annual ? "Billed yearly at" : "Billed monthly, over 12 months"}
</dt>
<dd className="font-semibold whitespace-nowrap tabular-nums">
{loading ? (
<span aria-hidden="true" className={cn("inline-block h-4 w-12 align-middle", SKELETON_CLASS)} />
) : (
money.format(perYear)
)}
</dd>
</div>
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted-foreground">
{annual ? "Against monthly billing" : "With annual billing"}
</dt>
<dd className="whitespace-nowrap tabular-nums">
{loading && (
<span aria-hidden="true" className={cn("inline-block h-4 w-12 align-middle", SKELETON_CLASS)} />
)}
{!loading && saving > 0 && (
<>
<bdi aria-hidden="true">
{"\u2212"}
{money.format(saving)} <span className="text-xs text-muted-foreground">/yr</span>
</bdi>
<span className="sr-only">{money.format(saving)} less per year</span>
</>
)}
{!loading && saving === 0 && <span className="text-muted-foreground">None</span>}
</dd>
</div>
</dl>
<ul className="mt-6 mb-6 flex flex-1 flex-col gap-2 text-sm">
{plan.features.map((feature) => (
<li key={feature} className="flex items-start gap-2">
<Check aria-hidden="true" className="mt-0.5 size-4 shrink-0" />
<span className="min-w-0 break-words">
<span className="sr-only">Included: </span>
{feature}
</span>
</li>
))}
</ul>
{loading ? (
<Button variant={variant} className="w-full" disabled>
{actionLabel}
</Button>
) : (
<Button variant={variant} className="w-full" asChild>
<a href={plan.href[interval]}>{actionLabel}</a>
</Button>
)}
</div>
)
}
export function BillingSwitchIntervalRadio({
title = "Pay monthly, or once a year for less",
plans = DEFAULT_PLANS,
value: valueProp,
defaultValue = "annual",
onValueChange,
currency = "USD",
locale = "en-US",
disabled = false,
disabledReason,
loading = false,
contactHref = "#sales",
recommendedLabel = "Recommended",
headingLevel = 2,
className,
...props
}: BillingSwitchIntervalRadioProps) {
const [interval, setInterval] = useControllableState<BillingInterval>({
value: valueProp,
defaultValue,
onChange: onValueChange,
})
const headingId = React.useId()
const groupName = React.useId()
const reasonId = React.useId()
const annual = interval === "annual"
// Every figure the block can show decides the decimals together, so a
// monthly share such as 71.60 never sits next to a bare 30.
const whole = plans
.flatMap((plan) => [plan.monthly, plan.annual, plan.annual / 12, yearlySaving(plan)])
.every((figure) => Number.isInteger(cents(figure)))
const money = new Intl.NumberFormat(locale, {
style: "currency",
currency,
minimumFractionDigits: whole ? 0 : 2,
maximumFractionDigits: whole ? 0 : 2,
})
const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 1 })
const rates = plans
.filter((plan) => plan.monthly > 0)
.map((plan) => percent.format(yearlySaving(plan) / (plan.monthly * 12)))
const bestRate = plans.reduce(
(best, plan) => (plan.monthly > 0 ? Math.max(best, yearlySaving(plan) / (plan.monthly * 12)) : best),
0
)
const uniform = rates.every((rate) => rate === rates[0])
// While prices load, no saving is claimed from figures the block is hiding.
const savingText =
bestRate > 0 && !loading ? `${uniform ? "" : "up to "}${percent.format(bestRate)}` : null
const lead = annual ? "Billed once a year." : "Billed every month."
const rest = loading
? "Prices are loading."
: annual
? `Each price is the monthly share of one yearly charge${savingText ? `, ${savingText} below monthly billing` : ""}.`
: savingText
? `Switch to annual and pay ${savingText} less over the year.`
: "The price is the same on either interval."
const announcement = plans
.map((plan) => `${plan.name} ${money.format(annual ? plan.annual / 12 : plan.monthly)} per month`)
.join(", ")
return (
<section
data-slot="billing-switch-interval-radio"
data-interval={interval}
aria-labelledby={headingId}
className={cn("@container", className)}
{...props}
>
<div className="mx-auto max-w-6xl px-4 py-12 @3xl:px-6">
<div className="flex flex-col gap-6 @3xl:flex-row @3xl:items-end @3xl:justify-between">
<div className="min-w-0">
<Heading id={headingId} level={headingLevel} className="text-2xl font-semibold tracking-tight text-balance @3xl:text-4xl">
{title}
</Heading>
{/* Rendered even with no plans, so the region exists before its content does. */}
<p
role="status"
className={cn("mt-4 max-w-prose text-base text-pretty text-muted-foreground", plans.length === 0 && "sr-only")}
>
{plans.length > 0 && (
<>
<span className="font-medium text-foreground">{lead}</span> {rest}
{!loading && <span className="sr-only"> {announcement}.</span>}
</>
)}
</p>
</div>
{plans.length > 0 && (
<fieldset
data-slot="billing-switch-interval-radio-control"
disabled={disabled}
aria-describedby={disabled && disabledReason ? reasonId : undefined}
className="min-w-0 shrink-0"
>
<legend className="pb-2 font-mono text-xs font-medium tracking-wider text-muted-foreground uppercase">
Billing interval
</legend>
<div className="grid grid-cols-2 gap-1 rounded-lg border border-foreground/50 p-1 @md:inline-flex">
{INTERVALS.map((option) => (
<label key={option.value} className={SEGMENT_CLASS}>
<input
type="radio"
className="sr-only"
name={groupName}
value={option.value}
checked={interval === option.value}
onChange={() => setInterval(option.value)}
/>
<span
aria-hidden="true"
className="flex size-4 shrink-0 items-center justify-center rounded-full border border-foreground/50 group-has-[:checked]:border-primary-foreground"
>
<span className="size-2 rounded-full bg-primary-foreground opacity-0 group-has-[:checked]:opacity-100" />
</span>
<span className="flex flex-wrap items-baseline gap-x-2">
{option.label}
{option.value === "annual" && savingText && (
<span className="font-normal">Save {savingText}</span>
)}
</span>
</label>
))}
</div>
{disabled && disabledReason && (
<p id={reasonId} className="mt-2 max-w-[40ch] text-sm text-muted-foreground">
{disabledReason}
</p>
)}
</fieldset>
)}
</div>
{plans.length > 0 ? (
<>
<ul
aria-busy={loading}
className="mt-10 grid gap-px overflow-hidden rounded-xl border border-border bg-border bg-clip-padding @2xl:grid-cols-2 @5xl:grid-cols-3"
>
{plans.map((plan) => (
<li key={plan.id} data-slot="billing-switch-interval-radio-plan" className="min-w-0 bg-background">
<BillingSwitchIntervalRadioPlan
plan={plan}
interval={interval}
money={money}
loading={loading}
recommendedLabel={recommendedLabel}
headingLevel={nextHeadingLevel(headingLevel)}
/>
</li>
))}
{[0, 1].map((index) => (
<li key={`filler-${index}`} aria-hidden="true" className={fillerClass(index, plans.length)} />
))}
</ul>
<p className="mt-6 text-sm text-muted-foreground">
Prices in {currency}, before tax. Move between plans or intervals at any time.{" "}
<a href={contactHref} className={LINK_CLASS}>
Talk to sales about a larger plan
</a>
</p>
</>
) : (
<div
data-slot="billing-switch-interval-radio-empty"
aria-busy={loading}
className="mt-10 flex flex-col items-center rounded-xl border border-dashed border-border px-6 py-12 text-center"
>
<Heading level={nextHeadingLevel(headingLevel)} className="text-lg font-semibold">
{loading ? "Loading plans" : "No plans are on sale right now"}
</Heading>
<p className="mt-1 max-w-[40ch] text-sm text-muted-foreground">
Plans and their monthly and annual prices will be listed here{" "}
{loading ? "in a moment" : "once they are published"}.
</p>
<Button variant="outline" className="mt-6" asChild>
<a href={contactHref}>Ask sales for a quote</a>
</Button>
</div>
)}
</div>
</section>
)
}
The demo in the preview, 130 lines
import {
BillingSwitchIntervalRadio,
type BillingPlan,
} from "@/components/blocks/billing-switch-interval-radio"
// Nine plans, three times the default, with a long name, long features, a five
// figure yearly charge, cents, uneven savings and one paid plan that saves nothing.
const OVERFLOW_PLANS: BillingPlan[] = [
{
id: "hobby",
name: "Hobby",
description: "For a personal site or a side project.",
monthly: 0,
annual: 0,
features: ["10 monitors", "Checks every 5 minutes"],
actionLabel: "Start on Hobby",
href: { monthly: "#hobby", annual: "#hobby" },
},
{
id: "team",
name: "Team with on-call scheduling and escalation policies",
description:
"For a product team with an on-call rota that covers nights, weekends and public holidays in two time zones.",
monthly: 30,
annual: 288,
features: [
"100 monitors",
"Checks every minute",
"Escalation to phone, SMS and chat with a repeat interval you choose per service",
],
actionLabel: "Start Team",
href: { monthly: "#team-monthly", annual: "#team-annual" },
recommended: true,
},
{
id: "scale",
name: "Scale",
description: "For several products watched from several regions.",
monthly: 89.5,
annual: 859.2,
features: ["500 monitors", "Checks every 30 seconds", "Probes in 12 regions"],
actionLabel: "Start Scale",
href: { monthly: "#scale-monthly", annual: "#scale-annual" },
},
{
id: "agency",
name: "Agency",
description: "For studios that watch client sites under one login.",
monthly: 400,
annual: 3600,
features: ["2,000 monitors", "A workspace per client", "Reports under your own name"],
actionLabel: "Start Agency",
href: { monthly: "#agency-monthly", annual: "#agency-annual" },
},
{
id: "enterprise",
name: "Enterprise",
description: "For regulated teams with a private probe network.",
monthly: 1249,
annual: 12480,
features: ["Unlimited monitors", "Private probes", "Audit log kept for 7 years"],
actionLabel: "Start Enterprise",
href: { monthly: "#enterprise-monthly", annual: "#enterprise-annual" },
},
{
id: "archive",
name: "Compliance archive",
description: "Long term storage of check results, priced the same on either interval.",
monthly: 15,
annual: 180,
features: ["Results kept for 10 years", "Export to your own bucket"],
actionLabel: "Add the archive",
href: { monthly: "#archive-monthly", annual: "#archive-annual" },
},
{
id: "status-pages",
name: "Status pages",
description: "Public and private status pages without any monitors.",
monthly: 12,
annual: 120,
features: ["5 status pages", "Subscriber updates by email"],
actionLabel: "Add status pages",
href: { monthly: "#status-pages-monthly", annual: "#status-pages-annual" },
},
{
id: "browser-checks",
name: "Browser checks",
description: "Scripted sign-in and checkout flows run in a real browser.",
monthly: 49,
annual: 499.8,
features: ["20,000 runs a month", "Screenshots on failure"],
actionLabel: "Add browser checks",
href: { monthly: "#browser-checks-monthly", annual: "#browser-checks-annual" },
},
{
id: "reseller",
name: "Reseller",
description: "For hosting companies that resell monitoring to their customers.",
monthly: 2400,
annual: 23040,
features: ["10,000 monitors", "Billing per customer", "A named support engineer"],
actionLabel: "Start Reseller",
href: { monthly: "#reseller-monthly", annual: "#reseller-annual" },
},
]
export default function BillingSwitchIntervalRadioDemo() {
return <BillingSwitchIntervalRadio headingLevel={1} />
}
export const scenarios = {
monthly: () => <BillingSwitchIntervalRadio headingLevel={1} defaultValue="monthly" />,
disabled: () => (
<BillingSwitchIntervalRadio
headingLevel={1}
disabled
disabledReason="Your workspace is on an annual contract until Mar 9, 2027. The interval can change at renewal."
/>
),
loading: () => <BillingSwitchIntervalRadio headingLevel={1} loading />,
empty: () => <BillingSwitchIntervalRadio headingLevel={1} plans={[]} />,
overflow: () => (
<BillingSwitchIntervalRadio
headingLevel={1}
title="Monitoring plans for one site, one team or a whole portfolio of client products"
plans={OVERFLOW_PLANS}
/>
),
"euro-german-locale": () => <BillingSwitchIntervalRadio headingLevel={1} currency="EUR" locale="de-DE" />,
}
Props13
- title
- string = "Pay monthly, or once a year for less"
- plans
- BillingPlan[] = DEFAULT_PLANS
- value
- BillingInterval
- defaultValue
- BillingInterval = "annual"
- onValueChange
- (value: BillingInterval) => void
- currency
- string = "USD"
- ISO 4217 code.
- locale
- string = "en-US"
- disabled
- boolean = false
- Locks the interval choice. Pair it with `disabledReason`.
- disabledReason
- string
- Sentence shown under the locked control.
- loading
- boolean = false
- Prices are on their way: figures become skeletons and the actions wait.
- contactHref
- string = "#sales"
- Target of the sales link under the plans and of the empty state action.
- recommendedLabel
- string = "Recommended"
- Marker on the plan flagged `recommended`.
- headingLevel
- HeadingLevel = 2
Also accepts every prop of Omit<React.ComponentProps<"section">, "title" | "defaultValue" | "onChange">.
Accessibility
- Pattern
- Pricing structure, Radio Group (APG, opens in a new tab), Landmarks and headings
- Keyboard
Keyboard support for Monthly and Annual Billing Switch Key Effect Tab Moves to the checked interval, then through each plan action and the sales link Arrow Left, Arrow Right, Arrow Up, Arrow Down Moves to the other interval and selects it, which reprices every plan Space Selects the focused interval Enter on a plan action Follows the checkout link for the selected interval - Screen reader
Section labelled by its heading. The interval is a fieldset of two native radios with a visible legend, each plan has its own heading, and the billing sentence is a status region that also reads out every new price. The region stays in the DOM when there are no plans.
- Announces: Billed once a year. Each price is the monthly share of one yearly charge, {saving} below monthly billing. {plan} {price} per month
- Announces: Billed every month. Switch to annual and pay {saving} less over the year. {plan} {price} per month
- Announces: Billed once a year. Prices are loading.
- Reduced motion
- No motion apart from the loading skeleton pulse, which is switched off. Colour transitions only.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies4
- button
- @hazine/heading
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.