Buttons

Toggle Button

A Radix toggle button that announces state via aria-pressed and crossfades its pressed styling in ~150ms.

Install

npx shadcn@latest add @paragon/toggle-button

toggle-button.tsx

"use client";

import * as React from "react";
import * as TogglePrimitive from "@radix-ui/react-toggle";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";

const toggleButtonVariants = cva(
  // Enumerated transition properties (never `all`) so a rapid re-toggle
  // retargets the crossfade from wherever it currently is instead of jumping.
  "relative inline-flex items-center justify-center gap-2 rounded-lg text-sm font-medium whitespace-nowrap text-muted-foreground transition-[color,background-color,box-shadow,scale] duration-150 ease-out outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 after:absolute after:top-1/2 after:left-1/2 after:size-full after:min-h-10 after:min-w-10 after:-translate-x-1/2 after:-translate-y-1/2",
  {
    variants: {
      variant: {
        default:
          "hover:bg-accent/60 hover:text-foreground data-[state=on]:bg-accent",
        outline:
          "bg-card shadow-border hover:text-foreground hover:shadow-border-hover dark:bg-secondary/30 data-[state=on]:bg-accent data-[state=on]:shadow-border-hover",
      },
      size: {
        default: "h-9 px-4 has-[>svg:first-child]:pl-3.5",
        sm: "h-8 px-3 text-[13px] has-[>svg:first-child]:pl-2.5",
        lg: "h-10 px-5 has-[>svg:first-child]:pl-4",
        icon: "size-9",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  },
);

export interface ToggleButtonProps
  extends React.ComponentProps<typeof TogglePrimitive.Root>,
    VariantProps<typeof toggleButtonVariants> {
  /** Disables press-scale feedback where the motion would distract. */
  static?: boolean;
}

/**
 * A two-state button built on Radix Toggle. State is announced via
 * `aria-pressed`; the pressed styling crossfades over ~150ms with enumerated
 * color/background/box-shadow transitions, so hammering the toggle retargets
 * smoothly instead of restarting. Icon-only usage requires an `aria-label`.
 */
function ToggleButton({
  className,
  variant,
  size,
  static: isStatic = false,
  ...props
}: ToggleButtonProps) {
  return (
    <TogglePrimitive.Root
      data-slot="toggle-button"
      className={cn(
        toggleButtonVariants({ variant, size }),
        !isStatic && "active:not-disabled:scale-[0.97]",
        className,
      )}
      {...props}
    />
  );
}

export { ToggleButton, toggleButtonVariants };