Components
Button Group
Groups related buttons into one control. Set the variant, size and disabled state once on the group and every Button inside follows.
Introduction
ButtonGroup wraps several Button components and lays them out as a single control: the corners between them are squared off and the borders overlap, so the buttons read as one segmented bar.
variant,sizeandisDisabledset on the group become the defaults of every button inside, and a button can still override them.- Horizontal or vertical, attached or spaced apart.
- Works with icon-only buttons, links and every Button size and variant.
- Exposed to assistive technology as a group. Each button stays its own tab stop.
Installation
centerUI has no CLI or registry yet: components are copied into your project. ButtonGroup is built on Button, so it needs everything Button needs.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxAdd Button first (see its Manual installation), then follow the steps below.
Manual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the ButtonGroup files
src/types/button-group-context.tsShow code
import { createContext, useContext } from "react";
import type { VariantProps } from "tailwind-variants";
import type { buttonStyles } from "./button-styles";
/** Defaults a ButtonGroup passes down to the buttons inside it. */
export type ButtonGroupContextValue = Pick<
VariantProps<typeof buttonStyles>,
"variant" | "size"
> & {
isDisabled?: boolean;
};
const ButtonGroupContext = createContext<ButtonGroupContextValue | null>(null);
export const ButtonGroupProvider = ButtonGroupContext.Provider;
/** The enclosing ButtonGroup's defaults, or null outside of one. */
export function useButtonGroup() {
return useContext(ButtonGroupContext);
}src/types/button-group-styles.tsShow code
import { tv } from "tailwind-variants";
// Attached groups square off the inner corners and overlap the neighbours by
// 1px so borders are not doubled. Solid buttons get a thin inner divider in
// the color each variant exposes as `--divider` (see button-styles.ts).
const attachedHorizontal = [
"[&>*:not(:first-child)]:-ml-px [&>*:not(:first-child)]:rounded-l-none",
"[&>*:not(:last-child)]:rounded-r-none",
"[&>*:not(:first-child)]:shadow-[inset_1px_0_0_color-mix(in_oklab,var(--divider,transparent)_30%,transparent)]",
];
const attachedVertical = [
"[&>*:not(:first-child)]:-mt-px [&>*:not(:first-child)]:rounded-t-none",
"[&>*:not(:last-child)]:rounded-b-none",
"[&>*:not(:first-child)]:shadow-[inset_0_1px_0_color-mix(in_oklab,var(--divider,transparent)_30%,transparent)]",
];
export const buttonGroupStyles = tv({
// Hovered and focused buttons rise above their neighbours so their outline
// and focus ring are never covered by the overlap.
base: "inline-flex [&>*:focus-visible]:z-10 [&>*:hover]:z-10",
variants: {
orientation: {
horizontal: "flex-row",
vertical: "flex-col",
},
isAttached: {
true: "",
false: "gap-2",
},
isFullWidth: {
true: "flex w-full [&>*]:grow [&>*]:basis-0",
false: "",
},
},
compoundVariants: [
{ orientation: "horizontal", isAttached: true, class: attachedHorizontal },
{ orientation: "vertical", isAttached: true, class: attachedVertical },
],
defaultVariants: {
orientation: "horizontal",
isAttached: true,
isFullWidth: false,
},
});src/components/ui/button-group/button-group.tsxShow code
"use client";
import { type ComponentPropsWithoutRef, useMemo } from "react";
import { cn } from "@/lib/cn";
import {
type ButtonGroupContextValue,
ButtonGroupProvider,
} from "@/types/button-group-context";
import { buttonGroupStyles } from "@/types/button-group-styles";
export interface ButtonGroupProps
extends ComponentPropsWithoutRef<"div">,
ButtonGroupContextValue {
/** Direction the buttons are laid out in. */
orientation?: "horizontal" | "vertical";
/** Join the buttons into one control. `false` keeps them apart with a gap. */
isAttached?: boolean;
/** Stretch the group to the full width, with equally wide buttons. */
isFullWidth?: boolean;
}
/**
* Lays out related Buttons as one unit. `variant`, `size` and `isDisabled` set
* here become the defaults of every Button inside; a Button can still override
* them with its own props. Give the group an accessible name with `aria-label`.
*
* @example
* <ButtonGroup variant="outline" aria-label="Text alignment">
* <Button>Left</Button>
* <Button>Center</Button>
* <Button>Right</Button>
* </ButtonGroup>
*/
export function ButtonGroup({
orientation = "horizontal",
isAttached = true,
isFullWidth = false,
variant,
size,
isDisabled,
className,
children,
...props
}: ButtonGroupProps) {
const defaults = useMemo(
() => ({ variant, size, isDisabled }),
[variant, size, isDisabled],
);
return (
<ButtonGroupProvider value={defaults}>
{/* biome-ignore lint/a11y/useSemanticElements: a div with role="group" is the standard pattern for a set of buttons; <fieldset> brings form styling quirks (legend, min-inline-size). */}
<div
role="group"
data-orientation={orientation}
{...props}
className={cn(
buttonGroupStyles({ orientation, isAttached, isFullWidth }),
className,
)}
>
{children}
</div>
</ButtonGroupProvider>
);
}2. Update Button
Button reads the group's defaults, and each variant exposes a --divider color used between attached solid buttons. Replace these two files with the versions below.
src/types/button-styles.tsShow code
import { tv } from "tailwind-variants";
// Kept out of button.tsx (a Client Component) so Server Components can call it
// to style links like buttons.
export const buttonStyles = tv({
base: [
"group relative isolate inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium",
"transition-colors outline-none",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
"data-disabled:pointer-events-none data-disabled:opacity-50",
"data-pending:cursor-progress data-pending:opacity-70",
"[&_svg]:pointer-events-none [&_svg]:shrink-0",
// Touch hitbox: on touch screens (coarse pointer) an invisible box grows
// the tappable area to at least 44x44px, without changing the layout.
"after:absolute after:top-1/2 after:left-1/2 after:size-[max(100%,2.75rem)] after:-translate-x-1/2 after:-translate-y-1/2 pointer-fine:after:hidden",
],
variants: {
variant: {
primary:
"[--divider:var(--primary-fg)] [--fx:var(--primary)] bg-primary text-primary-fg data-hovered:bg-primary/90 data-pressed:bg-primary/80 hover:bg-primary/90",
secondary:
"[--divider:var(--fg)] [--fx:var(--muted-fg)] bg-secondary text-secondary-fg data-hovered:bg-secondary/80 data-pressed:bg-secondary/60 hover:bg-secondary/80",
outline:
"[--fx:var(--fg)] border bg-transparent text-fg data-hovered:bg-muted data-pressed:bg-muted/70 hover:bg-muted",
ghost:
"[--fx:var(--fg)] text-fg data-hovered:bg-muted data-pressed:bg-muted/70 hover:bg-muted",
danger:
"[--divider:var(--danger-fg)] [--fx:var(--danger)] bg-danger text-danger-fg data-hovered:bg-danger/90 data-pressed:bg-danger/80 hover:bg-danger/90",
},
// Height, padding, text, gap, icon size and radius grow together.
size: {
xxs: "h-5 gap-1 px-1.5 text-[10px] [&_svg]:size-3",
xs: "h-6 gap-1.5 px-2 text-xs [&_svg]:size-3.5",
sm: "h-8 px-3 text-sm [&_svg]:size-4",
md: "h-9 px-4 text-sm [&_svg]:size-4",
lg: "h-11 px-6 text-base [&_svg]:size-5",
xl: "h-12 rounded-lg px-7 text-lg [&_svg]:size-5",
"2xl": "h-14 gap-2.5 rounded-lg px-8 text-xl [&_svg]:size-6",
"3xl": "h-16 gap-3 rounded-xl px-10 text-2xl [&_svg]:size-7",
"4xl": "h-20 gap-4 rounded-xl px-12 text-3xl [&_svg]:size-8",
icon: "size-9 [&_svg]:size-4",
},
// Square button for an icon on its own: same height as its size, and the
// width follows. Give it an accessible name (`aria-label`).
isIcon: {
true: "px-0",
false: "",
},
// Fully round: a circle for an icon on its own, a pill for a button with
// text. It is after `size` so it wins over the larger sizes' own radius.
isCircle: {
true: "rounded-full",
false: "",
},
},
compoundVariants: [
{ isIcon: true, size: "xxs", class: "size-5" },
{ isIcon: true, size: "xs", class: "size-6" },
{ isIcon: true, size: "sm", class: "size-8" },
{ isIcon: true, size: "md", class: "size-9" },
{ isIcon: true, size: "lg", class: "size-11" },
{ isIcon: true, size: "xl", class: "size-12" },
{ isIcon: true, size: "2xl", class: "size-14" },
{ isIcon: true, size: "3xl", class: "size-16" },
{ isIcon: true, size: "4xl", class: "size-20" },
],
defaultVariants: {
variant: "primary",
size: "md",
isIcon: false,
isCircle: false,
},
});src/components/ui/button/button.tsxShow code
"use client";
import Link from "next/link";
import { type ComponentProps, type ReactNode, useState } from "react";
import {
Button as AriaButton,
type ButtonProps as AriaButtonProps,
composeRenderProps,
} from "react-aria-components";
import type { VariantProps } from "tailwind-variants";
import { Loader } from "@/components/ui/loader/loader";
import { cn } from "@/lib/cn";
import { cx } from "@/lib/primitive";
import { useButtonGroup } from "@/types/button-group-context";
import { buttonStyles } from "@/types/button-styles";
import { useRipples } from "@/types/use-ripples";
import {
type ButtonEffectProps,
ButtonEffects,
hasEffect,
splitEffectProps,
} from "./button-effects";
type StyleProps = VariantProps<typeof buttonStyles> & ButtonEffectProps;
/** Rendered as a `<button>`. */
export interface ButtonProps extends AriaButtonProps, StyleProps {
href?: undefined;
}
/** Rendered as a link (`next/link`) that looks and animates like a button. */
export interface ButtonLinkProps
extends StyleProps,
Omit<ComponentProps<typeof Link>, "className" | "children"> {
className?: string;
children?: ReactNode;
}
type LoaderSize = "xs" | "sm" | "md" | "lg" | "xl";
// The loader that goes with each button size.
const loaderSizes: Record<string, LoaderSize> = {
xxs: "xs",
xs: "xs",
sm: "xs",
md: "sm",
icon: "sm",
lg: "md",
xl: "md",
"2xl": "lg",
"3xl": "lg",
"4xl": "xl",
};
// While the button is pending a loader goes before the label, which stays. An
// icon-only button has no label, so the loader takes the place of its icon.
function ButtonContent({
isPending,
isIcon,
size,
children,
}: {
isPending: boolean;
isIcon: boolean;
size: string;
children: ReactNode;
}) {
if (!isPending) return children;
return (
<>
<Loader
variant={"spinner"}
size={loaderSizes[size] ?? "sm"}
label={false}
/>
{isIcon ? null : children}
</>
);
}
const rainbowClasses = "text-white [text-shadow:0_1px_2px_oklch(0_0_0/0.4)]";
/**
* A button. Pass `href` to render a link instead, so navigation gets the same
* variants, sizes and effects.
*
* While it is pending it shows a loader before its label and ignores
* presses. Set `isPending` yourself, or return a promise from `onPress` and it
* is pending until the promise settles.
*
* @example
* <Button onPress={save}>Save</Button>
* <Button href="/docs" variant="outline">Read the docs</Button>
* <Button onPress={() => save()}>Save</Button> // pending while save() runs
*/
export function Button(props: ButtonProps | ButtonLinkProps) {
if (props.href !== undefined) {
return <LinkButton {...props} />;
}
return <ActionButton {...props} />;
}
function ActionButton(props: ButtonProps) {
const { fx, rest } = splitEffectProps(props);
const {
className,
variant,
size,
isIcon,
isCircle,
children,
onPointerDown,
onPress,
onPressStart,
isPending,
href: _href,
...ariaProps
} = rest;
const group = useButtonGroup();
// Pending while a promise returned by `onPress` has not settled, unless
// `isPending` says otherwise.
const [isRunning, setRunning] = useState(false);
const pending = isPending ?? isRunning;
const buttonSize = size ?? group?.size ?? "md";
const { ripples, fromPointer, fromCenter } = useRipples(fx.isRipple);
return (
<AriaButton
{...ariaProps}
isDisabled={ariaProps.isDisabled ?? group?.isDisabled}
isPending={pending}
onPress={(event) => {
const result: unknown = onPress?.(event);
if (result instanceof Promise) {
setRunning(true);
const done = () => setRunning(false);
result.then(done, done);
}
}}
onPointerDown={(event) => {
fromPointer(event);
onPointerDown?.(event);
}}
// Pointer presses are handled above (they carry a position). Keyboard
// presses have none, so the ripple starts from the center.
onPressStart={(event) => {
if (event.pointerType === "keyboard") fromCenter(event.target);
onPressStart?.(event);
}}
className={cx(
buttonStyles({
variant: variant ?? group?.variant,
size: size ?? group?.size,
isIcon,
isCircle,
}),
fx.isRainbow && rainbowClasses,
className,
)}
>
{composeRenderProps(children, (children) => {
const content = (
<ButtonContent
isPending={pending}
isIcon={Boolean(isIcon) || buttonSize === "icon"}
size={buttonSize}
>
{children}
</ButtonContent>
);
return hasEffect(fx) ? (
<ButtonEffects fx={fx} ripples={ripples}>
{content}
</ButtonEffects>
) : (
content
);
})}
</AriaButton>
);
}
function LinkButton(props: ButtonLinkProps) {
const { fx, rest } = splitEffectProps(props);
const {
className,
variant,
size,
isIcon,
isCircle,
children,
onPointerDown,
onKeyDown,
...linkProps
} = rest;
const group = useButtonGroup();
const { ripples, fromPointer, fromCenter } = useRipples(fx.isRipple);
return (
<Link
{...linkProps}
onPointerDown={(event) => {
fromPointer(event);
onPointerDown?.(event);
}}
onKeyDown={(event) => {
if (event.key === "Enter") fromCenter(event.currentTarget);
onKeyDown?.(event);
}}
className={cn(
buttonStyles({
variant: variant ?? group?.variant,
size: size ?? group?.size,
isIcon,
isCircle,
}),
fx.isRainbow && rainbowClasses,
className,
)}
>
{hasEffect(fx) ? (
<ButtonEffects fx={fx} ripples={ripples}>
{children}
</ButtonEffects>
) : (
children
)}
</Link>
);
}3. Use it
import { Button } from "@/components/ui/button/button";
import { ButtonGroup } from "@/components/ui/button-group/button-group";Anatomy
A group is a container and the buttons inside it.
<ButtonGroup variant="outline" aria-label="Text alignment">
<Button>Left</Button>
<Button>Center</Button>
<Button>Right</Button>
</ButtonGroup><div role="group" aria-label="Text alignment"> <!-- ButtonGroup -->
<button>Left</button> <!-- Button -->
<button>Center</button>
<button>Right</button>
</div>| Part | Rendered as | Notes |
|---|---|---|
| Group | div with role=group | Lays the buttons out, joins their corners, and passes variant, size and isDisabled down. |
| Button | button, or a link with href | Any number of Button components. Each one keeps its own press and focus behavior. |
Give the group an accessible name with aria-label (or aria-labelledby) so a screen reader announces what the buttons belong to.
Examples
Live previews with code you can copy.
Usage
Orientation
Stack the buttons with orientation.
Spacing
Set isAttached to false to keep the buttons apart, each with its own corners.
Variants
Solid variants get a thin divider between the buttons.
Overriding a button
A prop on a Button wins over the group's default.
Sizes
Disabled
Disable the whole group, or a single button inside it.
Full width
The group fills its container and the buttons share the width equally.
Links
Buttons with href work inside a group too.
Component API
ButtonGroup accepts every prop of a div, plus the ones below.
| Prop | Type | Default |
|---|---|---|
| orientation | "horizontal" | "vertical" | "horizontal" |
| isAttached | boolean | true |
| isFullWidth | boolean | false |
| variant | "primary" | "secondary" | "outline" | "ghost" | "danger" | - |
| size | "xxs" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl" | "icon" | - |
| isDisabled | boolean | false |
| aria-label | string | - |
| className | string | - |