Skip to content

Button Group

A set of buttons grouped together in a single line with consistent styling and spacing.

Installation

Add Button Group to your project with the CK-UI CLI. It copies the source into your project, so the code is yours to change.

Terminal
npx ck-ui-cli@latest add button-group
Adds
ButtonGroup.tsxButton.tsxto your CK-UI folder (src/components/ck-ui by default)
Installs
@radix-ui/react-slotclass-variance-authorityif your project does not have them yet

First time with CK-UI in this project? Run npx ck-ui-cli@latest init once before adding components. The installation guide explains what it sets up.

Manual installationInstall the packages and copy the files yourself.

Install the following dependencies

Run these commands in your terminal to install the required packages

Terminal
npm install @radix-ui/react-slot class-variance-authority

Add the Button component

ButtonGroup imports ./Button, so add this file next to it

/components/ui/Button.tsx
import * as React from "react";
import Link from "next/link";
import { Slot } from "@radix-ui/react-slot";
import { cva } from "class-variance-authority";
import { cn } from "@/lib/utils";

// Server-compatible: no hooks or context, so Button can be rendered from server components.

export type ButtonVariant = "default" | "stroke" | "lighter" | "ghost";
export type ButtonColor = "primary" | "neutral" | "destructive" | "success";
export type ButtonSize = "xs" | "sm" | "md" | "lg";

/** @deprecated Use `primary` / `destructive`. */
type LegacyButtonColor = "blue" | "danger";
/** @deprecated Use `xs` / `sm` / `md` / `lg`. */
type LegacyButtonSize = "x-small" | "small" | "medium" | "large";

const LEGACY_COLORS: Record<LegacyButtonColor, ButtonColor> = { blue: "primary", danger: "destructive" };
const LEGACY_SIZES: Record<LegacyButtonSize, ButtonSize> = { "x-small": "xs", small: "sm", medium: "md", large: "lg" };

export function resolveButtonColor(color?: ButtonColor | LegacyButtonColor | null): ButtonColor {
    if (!color) return "primary";
    return color in LEGACY_COLORS ? LEGACY_COLORS[color as LegacyButtonColor] : (color as ButtonColor);
}

export function resolveButtonSize(size?: ButtonSize | LegacyButtonSize | null): ButtonSize {
    if (!size) return "md";
    return size in LEGACY_SIZES ? LEGACY_SIZES[size as LegacyButtonSize] : (size as ButtonSize);
}

const buttonRootVariants = cva(
    [
        "group/button relative flex items-center justify-center whitespace-nowrap rounded-lg border size-label-sm",
        "transition-colors duration-base ease-standard focus-ring",
        "disabled:cursor-not-allowed disabled:border-transparent disabled:bg-muted disabled:text-muted-foreground",
        "aria-disabled:pointer-events-none aria-disabled:cursor-not-allowed aria-disabled:border-transparent aria-disabled:bg-muted aria-disabled:text-muted-foreground",
    ],
    {
        variants: {
            variant: {
                default: "border-transparent",
                stroke: "bg-transparent hover:border-transparent",
                lighter: "border-transparent",
                ghost: "border-transparent bg-transparent",
            },
            color: {
                primary: "",
                neutral: "",
                destructive: "",
                success: "",
            },
            size: {
                lg: "h-10 min-w-10 gap-3 px-3",
                md: "h-9 min-w-9 gap-2.5 px-2.5",
                sm: "h-8 min-w-8 gap-2 px-2",
                xs: "h-7 min-w-7 gap-2 px-1.5",
            },
        },
        defaultVariants: {
            variant: "default",
            color: "primary",
            size: "md",
        },
        compoundVariants: [
            // Default (filled)
            { variant: "default", color: "primary", class: "bg-primary text-primary-foreground hover:bg-primary-hover" },
            { variant: "default", color: "neutral", class: "bg-secondary text-secondary-foreground hover:bg-secondary-hover" },
            { variant: "default", color: "destructive", class: "bg-destructive text-destructive-foreground hover:bg-destructive-hover" },
            { variant: "default", color: "success", class: "bg-success text-success-foreground hover:bg-success-hover" },

            // Stroke, lighter and ghost colour their text with the -strong shade (AA on background and -subtle).
            { variant: "stroke", color: "primary", class: "border-primary-border text-primary-strong hover:bg-primary-subtle" },
            { variant: "stroke", color: "neutral", class: "border-border text-muted-foreground hover:bg-muted hover:text-foreground" },
            { variant: "stroke", color: "destructive", class: "border-destructive-border text-destructive-strong hover:bg-destructive-subtle" },
            { variant: "stroke", color: "success", class: "border-success-border text-success-strong hover:bg-success-subtle" },

            // Lighter
            { variant: "lighter", color: "primary", class: "bg-primary-subtle text-primary-strong hover:border-primary-border hover:bg-transparent" },
            { variant: "lighter", color: "neutral", class: "bg-muted text-muted-foreground hover:border-border hover:bg-transparent hover:text-foreground" },
            { variant: "lighter", color: "destructive", class: "bg-destructive-subtle text-destructive-strong hover:border-destructive-border hover:bg-transparent" },
            { variant: "lighter", color: "success", class: "bg-success-subtle text-success-strong hover:border-success-border hover:bg-transparent" },

            // Ghost
            { variant: "ghost", color: "primary", class: "text-primary-strong hover:bg-primary-subtle" },
            { variant: "ghost", color: "neutral", class: "text-muted-foreground hover:bg-muted hover:text-foreground" },
            { variant: "ghost", color: "destructive", class: "text-destructive-strong hover:bg-destructive-subtle" },
            { variant: "ghost", color: "success", class: "text-success-strong hover:bg-success-subtle" },
        ],
    }
);

// Without an explicit size, Button.Icon follows the parent Button's data-size (pure CSS, works with asChild).
const buttonIconVariants = cva("flex shrink-0 items-center justify-center", {
    variants: {
        size: {
            inherit: "size-5 group-data-[size=sm]/button:size-4 group-data-[size=xs]/button:size-4",
            lg: "size-5",
            md: "size-5",
            sm: "size-4",
            xs: "size-4",
        },
    },
    defaultVariants: {
        size: "inherit",
    },
});

export interface ButtonRootProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "color"> {
    /** Render the single child element instead of a <button>, merging Button's props onto it. */
    asChild?: boolean;
    variant?: ButtonVariant;
    color?: ButtonColor | LegacyButtonColor;
    size?: ButtonSize | LegacyButtonSize;
    /** Disables the button and marks it busy while an action runs. */
    loading?: boolean;
    /** Render a Next.js link styled as a button. */
    href?: string;
}

function LoadingIndicator() {
    return (
        <svg className="size-4 shrink-0 animate-spin" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="3" />
            <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
        </svg>
    );
}

const ButtonRoot = React.forwardRef<HTMLButtonElement, ButtonRootProps>(
    ({ asChild = false, className, variant, color, size, loading = false, href, disabled, type, children, ...props }, ref) => {
        const resolvedSize = resolveButtonSize(size);
        const classes = cn(buttonRootVariants({ variant, color: resolveButtonColor(color), size: resolvedSize }), className);
        const isDisabled = Boolean(disabled || loading);

        if (asChild) {
            return (
                <Slot ref={ref} className={classes} data-size={resolvedSize} aria-disabled={isDisabled || undefined} aria-busy={loading || undefined} {...props}>
                    {children}
                </Slot>
            );
        }

        if (href !== undefined) {
            const anchorProps = props as React.AnchorHTMLAttributes<HTMLAnchorElement>;
            const anchorRef = ref as unknown as React.Ref<HTMLAnchorElement>;

            // A disabled link has no href, so it cannot be followed or focused.
            if (isDisabled) {
                return (
                    <a ref={anchorRef} className={classes} data-size={resolvedSize} aria-disabled="true" aria-busy={loading || undefined} {...anchorProps}>
                        {loading && <LoadingIndicator />}
                        {children}
                    </a>
                );
            }

            return (
                <Link ref={anchorRef} href={href} className={classes} data-size={resolvedSize} {...anchorProps}>
                    {children}
                </Link>
            );
        }

        return (
            <button ref={ref} type={type ?? "button"} className={classes} data-size={resolvedSize} disabled={isDisabled} aria-busy={loading || undefined} {...props}>
                {loading && <LoadingIndicator />}
                {children}
            </button>
        );
    }
);
ButtonRoot.displayName = "Button.Root";

export interface ButtonIconProps extends React.HTMLAttributes<HTMLElement> {
    size?: ButtonSize | LegacyButtonSize;
    /** Element or icon component to render, e.g. `as={RiAddLine}`. */
    as?: React.ElementType;
}

const ButtonIcon = React.forwardRef<HTMLElement, ButtonIconProps>(({ as: Component = "span", className, size, ...props }, ref) => {
    return <Component ref={ref} aria-hidden="true" className={cn(buttonIconVariants({ size: size ? resolveButtonSize(size) : "inherit" }), className)} {...props} />;
});
ButtonIcon.displayName = "Button.Icon";

const Button = {
    Root: ButtonRoot,
    Icon: ButtonIcon,
};

export { Button, ButtonRoot as Root, ButtonIcon as Icon, buttonRootVariants, buttonIconVariants };
export default Button;

Create or update your ButtonGroup component

Copy this code to create your ButtonGroup component

/components/ui/ButtonGroup.tsx
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cn } from "@/lib/utils";
import { resolveButtonSize, type ButtonSize } from "./Button";

// Server-compatible: no hooks, context or cloneElement.
// Root publishes its size and shape as CSS custom properties (and typography, which buttons inherit);
// Items and Icons read them with fallbacks to the `md` values. Because the consuming classes are plain
// arbitrary-value utilities that read these properties, a consumer className such as `px-8` still wins through cn().

/** @deprecated Use `xs` / `sm` / `md` / `lg`. */
type LegacyButtonGroupSize = "x-small" | "small" | "medium" | "large";
export type ButtonGroupSize = ButtonSize;

const SIZE_VARS: Record<ButtonGroupSize, string> = {
    lg: "[--button-group-item-height:2.25rem] [--button-group-item-padding:1rem] [--button-group-item-gap:1rem] [--button-group-icon-size:1.25rem] [--button-group-icon-margin:-0.5rem]",
    md: "[--button-group-item-height:2rem] [--button-group-item-padding:0.875rem] [--button-group-item-gap:0.875rem] [--button-group-icon-size:1rem] [--button-group-icon-margin:-0.5rem]",
    sm: "[--button-group-item-height:1.75rem] [--button-group-item-padding:0.875rem] [--button-group-item-gap:0.875rem] [--button-group-icon-size:0.875rem] [--button-group-icon-margin:-0.5rem]",
    xs: "[--button-group-item-height:1.75rem] [--button-group-item-padding:0.375rem] [--button-group-item-gap:0.5rem] [--button-group-icon-size:1rem] [--button-group-icon-margin:0px]",
};

const ICON_SIZE_VARS: Record<ButtonGroupSize, string> = {
    lg: "[--button-group-icon-size:1.25rem] [--button-group-icon-margin:-0.5rem]",
    md: "[--button-group-icon-size:1rem] [--button-group-icon-margin:-0.5rem]",
    sm: "[--button-group-icon-size:0.875rem] [--button-group-icon-margin:-0.5rem]",
    xs: "[--button-group-icon-size:1rem] [--button-group-icon-margin:0px]",
};

// Buttons inherit font settings (Tailwind preflight), so typography set on Root applies to every Item.
const SIZE_TYPOGRAPHY: Record<ButtonGroupSize, string> = {
    lg: "size-label-sm",
    md: "size-label-sm",
    sm: "size-label-xs",
    xs: "size-label-xs",
};

const ROUNDED_VARS = {
    default: "[--button-group-radius:0.5rem]",
    full: "[--button-group-radius:9999px]",
};

const buttonGroupItemClasses = [
    "relative flex items-center justify-center whitespace-nowrap text-center",
    "h-[var(--button-group-item-height,2rem)] min-w-[var(--button-group-item-height,2rem)] gap-[var(--button-group-item-gap,0.875rem)] px-[var(--button-group-item-padding,0.875rem)]",
    "first:rounded-l-[var(--button-group-radius,0.5rem)] last:rounded-r-[var(--button-group-radius,0.5rem)]",
    "border border-border bg-background text-gray-600 dark:text-neutral-400",
    "transition duration-base ease-standard",
    "hover:bg-gray-100 dark:hover:bg-neutral-800",
    "focus-ring focus-visible:z-10",
    "data-[state=on]:bg-gray-200 data-[state=on]:text-foreground dark:data-[state=on]:bg-neutral-700 dark:data-[state=on]:text-foreground",
    "disabled:pointer-events-none disabled:bg-muted disabled:text-muted-foreground disabled:opacity-50",
    "aria-disabled:pointer-events-none aria-disabled:bg-muted aria-disabled:text-muted-foreground aria-disabled:opacity-50",
];

const buttonGroupIconClasses = "shrink-0 size-[var(--button-group-icon-size,1rem)] mx-[var(--button-group-icon-margin,-0.5rem)]";

export interface ButtonGroupRootProps extends React.HTMLAttributes<HTMLDivElement> {
    /** Size of every item in the group. */
    size?: ButtonGroupSize | LegacyButtonGroupSize;
    /** Pill-shaped outer corners. */
    roundedFull?: boolean;
}

const ButtonGroupRoot = React.forwardRef<HTMLDivElement, ButtonGroupRootProps>(({ className, size, roundedFull = false, ...props }, ref) => {
    const resolvedSize = resolveButtonSize(size);

    return (
        <div
            ref={ref}
            role="group"
            data-size={resolvedSize}
            data-rounded={roundedFull ? "full" : undefined}
            className={cn(
                "flex -space-x-[1.5px]",
                SIZE_VARS[resolvedSize],
                SIZE_TYPOGRAPHY[resolvedSize],
                roundedFull ? ROUNDED_VARS.full : ROUNDED_VARS.default,
                className
            )}
            {...props}
        />
    );
});
ButtonGroupRoot.displayName = "ButtonGroup.Root";

export interface ButtonGroupItemProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
    /** Marks the item as the current selection: sets `aria-pressed` and `data-state="on" | "off"`. Leave undefined for plain action buttons. */
    active?: boolean;
    /** Render the single child element instead of a <button>, merging the item's props onto it. */
    asChild?: boolean;
    /** @deprecated Set `size` on ButtonGroup.Root. Overrides the group size for this item (and its icons) only. */
    size?: ButtonGroupSize | LegacyButtonGroupSize;
    /** @deprecated Set `roundedFull` on ButtonGroup.Root. */
    roundedFull?: boolean;
}

const ButtonGroupItem = React.forwardRef<HTMLButtonElement, ButtonGroupItemProps>(
    ({ className, active, asChild = false, size, roundedFull, disabled, type, children, ...props }, ref) => {
        const ownSize = size ? resolveButtonSize(size) : undefined;
        const classes = cn(
            buttonGroupItemClasses,
            ownSize && [SIZE_VARS[ownSize], SIZE_TYPOGRAPHY[ownSize]],
            roundedFull !== undefined && (roundedFull ? ROUNDED_VARS.full : ROUNDED_VARS.default),
            className
        );
        const state = active === undefined ? undefined : active ? "on" : "off";

        if (asChild) {
            return (
                <Slot ref={ref} className={classes} aria-pressed={active} data-state={state} aria-disabled={disabled || undefined} {...props}>
                    {children}
                </Slot>
            );
        }

        return (
            <button ref={ref} type={type ?? "button"} className={classes} aria-pressed={active} data-state={state} disabled={disabled} {...props}>
                {children}
            </button>
        );
    }
);
ButtonGroupItem.displayName = "ButtonGroup.Item";

export interface ButtonGroupIconProps extends React.HTMLAttributes<HTMLElement> {
    /** Overrides the size inherited from ButtonGroup.Root. */
    size?: ButtonGroupSize | LegacyButtonGroupSize;
    /** Element or icon component to render, e.g. `as={RiBold}`. Defaults to a <span>. */
    as?: React.ElementType;
}

const ButtonGroupIcon = React.forwardRef<HTMLElement, ButtonGroupIconProps>(({ as: Component = "span", className, size, ...props }, ref) => {
    return <Component ref={ref} aria-hidden="true" className={cn(buttonGroupIconClasses, size && ICON_SIZE_VARS[resolveButtonSize(size)], className)} {...props} />;
});
ButtonGroupIcon.displayName = "ButtonGroup.Icon";

const ButtonGroup = {
    Root: ButtonGroupRoot,
    Item: ButtonGroupItem,
    Icon: ButtonGroupIcon,
};

export { ButtonGroup, ButtonGroupRoot as Root, ButtonGroupItem as Item, ButtonGroupIcon as Icon };
export default ButtonGroup;

Test Your Component

  • 1. Add the component to a test page
  • 2. Check all props and variants work as expected
  • 3. Verify responsive behavior
  • 4. Test with different content/data
  • 5. Ensure accessibility features work correctly

Sizes

Set size on the Root (xs, sm, md or lg); every item and icon in the group follows it.

Rounded Full

For a more modern look, you can use the rounded full variant which applies pill-shaped corners to the outer buttons.

Active State

Mark the current selection with active. Active items get aria-pressed="true" (others with active={false} get aria-pressed="false") and a matching data-state for styling. Manage which item is active in your own state.

Disabled State

Disable individual items with disabled when certain actions are not available. Disabled items are skipped by keyboard focus.

Examples

Here are some common usage examples of button groups in different contexts.

API Reference

The ButtonGroup component groups related buttons with consistent styling. Give the group an accessible name with aria-label, and give icon-only items their own aria-label.

ButtonGroup.Root

Container element that holds and styles a group of related buttons.

PropTypeDefaultDescription
size
"xs""sm""md""lg"
"md"

Size of every item in the group. The legacy names x-small, small, medium and large are still accepted.

roundedFull"boolean""false"

Pill-shaped outer corners

aria-label"string""undefined"

Accessible name of the group. Root renders role="group" (override with role, e.g. "toolbar").

ButtonGroup.Item

A native button inside the group (type="button" by default) with the shared keyboard focus ring.

PropTypeDefaultDescription
active"boolean""undefined"

Marks the item as the current selection: sets aria-pressed and data-state="on" | "off". Leave undefined for plain action buttons.

disabled"boolean""false"

Disables this item

type
"button""submit""reset"
"button"

Native button type; items do not submit forms unless asked to

asChild"boolean""false"

Render the single child element (e.g. a link) with the item styles and state merged onto it

aria-label"string""undefined"

Required for icon-only items

ButtonGroup.Icon

A decorative icon (aria-hidden) sized to match the group.

PropTypeDefaultDescription
as"React.ElementType"""span""

Icon component or element type to render, e.g. as={RiBold}

size
"xs""sm""md""lg"
"inherited"

Overrides the size inherited from ButtonGroup.Root