Button Group
A React button group built on shadcn/ui: join buttons, inputs and select triggers into one control with shared borders, horizontal or vertical — plus Motion blocks for a split button that rolls to the action you pick and a segmented button group with a sliding active indicator.
- Drop-in shadcn API
- Server Component friendly
- Horizontal & vertical
- Split button
- Motion blocks
"use client";
import * as React from "react";
import { CalendarDaysIcon, ColumnsIcon, LayoutGridIcon, ListIcon } from "lucide-react";
import { AnimatedButtonGroup } from "@/components/dusk/button-group/animated-button-group";
export default function AnimatedButtonGroupDemo() {
const [view, setView] = React.useState("board");
return (
<div className="flex flex-col items-center gap-6">
<AnimatedButtonGroup
aria-label="View"
value={view}
onValueChange={setView}
options={[
{ value: "list", label: <span className="max-sm:sr-only">List</span>, icon: <ListIcon /> },
{ value: "board", label: <span className="max-sm:sr-only">Board</span>, icon: <ColumnsIcon /> },
{ value: "calendar", label: <span className="max-sm:sr-only">Calendar</span>, icon: <CalendarDaysIcon /> },
{ value: "grid", label: <span className="max-sm:sr-only">Gallery</span>, icon: <LayoutGridIcon /> },
]}
/>
<AnimatedButtonGroup
aria-label="Time range"
size="sm"
defaultValue="7d"
options={[
{ value: "24h", label: "24h" },
{ value: "7d", label: "7d" },
{ value: "30d", label: "30d" },
{ value: "90d", label: "90d" },
]}
/>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/button-group.json1. Install the dependencies.
npm install @radix-ui/react-slot class-variance-authority2. Copy the source into
components/ui/button-group.tsx.button-group.tsx import * as React from "react"; import { Slot } from "@radix-ui/react-slot"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; /** * DuskUI Button Group — a drop-in upgrade of the shadcn/ui Button Group. * * Same parts, props and data-slot attributes as shadcn (ButtonGroup, * ButtonGroupSeparator, ButtonGroupText) plus: * - Joined DuskUI Buttons press as one surface: the press scale is swapped * for a 1px sink, so seams never pull apart mid-click. * - The focused or hovered segment rises above its neighbours, so its ring * and border are never clipped. * - Works with Inputs, Select triggers and nested groups (nested groups get * a gap, so a toolbar is one ButtonGroup of ButtonGroups). * - `orientation`: horizontal or vertical. * CSS only, so it works in Server Components. */ const buttonGroupVariants = cva( [ "flex w-fit items-stretch", "[&>*]:relative [&>*]:hover:z-[1] [&>*]:focus-visible:z-10 [&>*:focus-within]:z-10", "[&>[data-slot=button]]:active:scale-100 [&>[data-slot=button]]:active:translate-y-px motion-reduce:[&>[data-slot=button]]:active:translate-y-0", "[&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1", "has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md", "has-[>[data-slot=button-group]]:gap-2", ], { variants: { orientation: { horizontal: "[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none", vertical: "flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none", }, }, defaultVariants: { orientation: "horizontal" }, } ); /** Joins Buttons, Inputs and Select triggers into one control. */ function ButtonGroup({ className, orientation = "horizontal", ...props }: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) { return ( <div role="group" data-slot="button-group" data-orientation={orientation} className={cn(buttonGroupVariants({ orientation }), className)} {...props} /> ); } /** A non-interactive segment for a label, prefix or unit. `asChild` to render a `<label>`. */ function ButtonGroupText({ className, asChild = false, ...props }: React.ComponentProps<"div"> & { asChild?: boolean }) { const Comp = asChild ? Slot : "div"; return ( <Comp data-slot="button-group-text" className={cn( "flex items-center gap-2 rounded-md border bg-muted px-4 text-sm font-medium text-muted-foreground shadow-xs", "[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4", className )} {...props} /> ); } /** * A hairline between segments — needed between filled buttons (default, * secondary) that have no border of their own. Decorative. */ function ButtonGroupSeparator({ className, orientation = "vertical", ...props }: React.ComponentProps<"div"> & { orientation?: "horizontal" | "vertical" }) { return ( <div aria-hidden data-slot="button-group-separator" data-orientation={orientation} className={cn( "relative z-[2] !m-0 shrink-0 self-stretch bg-input", "data-[orientation=vertical]:w-px data-[orientation=horizontal]:h-px", className )} {...props} /> ); } export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants };
CSS only — no "use client" needed. Works with any button, but is tuned for the DuskUI Button: joined segments sink by a pixel instead of scaling, so seams never split.
Usage
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
export function Pager() {
return (
<ButtonGroup aria-label="Pagination">
<Button variant="outline">Previous</Button>
<Button variant="outline">Next</Button>
</ButtonGroup>
)
}Examples
Nested groups
A ButtonGroup of ButtonGroups becomes a toolbar with gaps between sets. ButtonGroupText adds a non-interactive segment.
import { ArchiveIcon, ChevronLeftIcon, ChevronRightIcon, ClockIcon, Trash2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ButtonGroup, ButtonGroupText } from "@/components/ui/button-group";
export default function ButtonGroupBasicDemo() {
return (
<div className="flex flex-col items-center gap-4">
<ButtonGroup aria-label="Message actions" className="flex-wrap justify-center gap-y-2">
<ButtonGroup>
<Button variant="outline" size="icon" aria-label="Previous message">
<ChevronLeftIcon />
</Button>
<ButtonGroupText className="px-3 tabular-nums">3 / 12</ButtonGroupText>
<Button variant="outline" size="icon" aria-label="Next message">
<ChevronRightIcon />
</Button>
</ButtonGroup>
<ButtonGroup>
<Button variant="outline">
<ArchiveIcon />
Archive
</Button>
<Button variant="outline">
<ClockIcon />
Snooze
</Button>
<Button variant="outline" size="icon" aria-label="Delete" className="hover:text-destructive">
<Trash2Icon />
</Button>
</ButtonGroup>
</ButtonGroup>
</div>
);
}Orientation & separators
orientation="vertical" stacks the buttons. Filled variants have no border, so put a ButtonGroupSeparator between them.
import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon, MinusIcon, PlusIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ButtonGroup, ButtonGroupSeparator } from "@/components/ui/button-group";
export default function ButtonGroupOrientationDemo() {
return (
<div className="flex items-center gap-8">
<ButtonGroup orientation="vertical" aria-label="Zoom">
<Button variant="outline" size="icon" aria-label="Zoom in">
<PlusIcon />
</Button>
<Button variant="outline" size="icon" aria-label="Zoom out">
<MinusIcon />
</Button>
</ButtonGroup>
<ButtonGroup aria-label="Text alignment">
<Button variant="secondary" size="icon" aria-label="Align left">
<AlignLeftIcon />
</Button>
<ButtonGroupSeparator />
<Button variant="secondary" size="icon" aria-label="Align center">
<AlignCenterIcon />
</Button>
<ButtonGroupSeparator />
<Button variant="secondary" size="icon" aria-label="Align right">
<AlignRightIcon />
</Button>
</ButtonGroup>
</div>
);
}With input & select
Inputs stretch to fill the group, and select triggers join seamlessly.
import { SearchIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
export default function ButtonGroupInputDemo() {
return (
<ButtonGroup className="w-full max-w-md">
<Select defaultValue="issues">
<SelectTrigger aria-label="Search in">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="issues">Issues</SelectItem>
<SelectItem value="pulls">Pull requests</SelectItem>
<SelectItem value="docs">Docs</SelectItem>
</SelectContent>
</Select>
<Input placeholder="Search…" aria-label="Search query" />
<Button variant="outline" size="icon" aria-label="Search">
<SearchIcon />
</Button>
</ButtonGroup>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Animated Button Group
Joined outline buttons where a quiet indicator slides to the selected segment. It's a radio group under the hood: one Tab stop, arrow keys and Home / End move the selection, and the value can be submitted with a form.
"use client";
import * as React from "react";
import { CalendarDaysIcon, ColumnsIcon, LayoutGridIcon, ListIcon } from "lucide-react";
import { AnimatedButtonGroup } from "@/components/dusk/button-group/animated-button-group";
export default function AnimatedButtonGroupDemo() {
const [view, setView] = React.useState("board");
return (
<div className="flex flex-col items-center gap-6">
<AnimatedButtonGroup
aria-label="View"
value={view}
onValueChange={setView}
options={[
{ value: "list", label: <span className="max-sm:sr-only">List</span>, icon: <ListIcon /> },
{ value: "board", label: <span className="max-sm:sr-only">Board</span>, icon: <ColumnsIcon /> },
{ value: "calendar", label: <span className="max-sm:sr-only">Calendar</span>, icon: <CalendarDaysIcon /> },
{ value: "grid", label: <span className="max-sm:sr-only">Gallery</span>, icon: <LayoutGridIcon /> },
]}
/>
<AnimatedButtonGroup
aria-label="Time range"
size="sm"
defaultValue="7d"
options={[
{ value: "24h", label: "24h" },
{ value: "7d", label: "7d" },
{ value: "30d", label: "30d" },
{ value: "90d", label: "90d" },
]}
/>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-button-group.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/button-group/animated-button-group.tsx.animated-button-group.tsx "use client"; import * as React from "react"; import { LayoutGroup, motion, useReducedMotion, type Transition } from "motion/react"; import { buttonVariants } from "@/components/ui/button"; import { ButtonGroup } from "@/components/ui/button-group"; import { cn } from "@/lib/utils"; export interface AnimatedButtonGroupOption { value: string; /** Visible label. Omit for an icon-only segment, but then set `aria-label`. */ label?: React.ReactNode; icon?: React.ReactNode; "aria-label"?: string; disabled?: boolean; } export interface AnimatedButtonGroupProps extends Omit<React.ComponentProps<"div">, "onChange" | "defaultValue" | "dir"> { options: AnimatedButtonGroupOption[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Form field name. The selected value is submitted with a hidden input. */ name?: string; size?: "sm" | "default" | "lg"; orientation?: "horizontal" | "vertical"; disabled?: boolean; } const indicatorSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const iconSizes = { sm: "icon-sm", default: "icon", lg: "icon-lg" } as const; /** * Joined outline buttons where the selected one is marked by an indicator * that slides between segments on a spring. It behaves like a radio group: * one Tab stop, arrow keys (and Home / End) move and select, and the value * can be submitted with a form. Under reduced motion the indicator jumps. */ export function AnimatedButtonGroup({ options, value: valueProp, defaultValue, onValueChange, name, size = "default", orientation = "horizontal", disabled = false, className, ...props }: AnimatedButtonGroupProps) { const id = React.useId(); const reduceMotion = useReducedMotion() ?? false; const refs = React.useRef<Array<HTMLButtonElement | null>>([]); const [uncontrolled, setUncontrolled] = React.useState(defaultValue ?? options[0]?.value ?? ""); const value = valueProp ?? uncontrolled; const select = (next: string) => { if (next === value) return; if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }; const enabled = options.map((option, index) => ({ option, index })).filter(({ option }) => !option.disabled); const onKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>, index: number) => { const prevKeys = orientation === "vertical" ? ["ArrowUp"] : ["ArrowLeft", "ArrowUp"]; const nextKeys = orientation === "vertical" ? ["ArrowDown"] : ["ArrowRight", "ArrowDown"]; const position = enabled.findIndex((entry) => entry.index === index); let target: number | undefined; if (nextKeys.includes(event.key)) target = enabled[(position + 1) % enabled.length]?.index; else if (prevKeys.includes(event.key)) target = enabled[(position - 1 + enabled.length) % enabled.length]?.index; else if (event.key === "Home") target = enabled[0]?.index; else if (event.key === "End") target = enabled[enabled.length - 1]?.index; if (target === undefined) return; event.preventDefault(); refs.current[target]?.focus(); select(options[target].value); }; const hasSelection = options.some((option) => option.value === value && !option.disabled); return ( <LayoutGroup id={id}> <ButtonGroup role="radiogroup" aria-orientation={orientation} aria-disabled={disabled || undefined} orientation={orientation} className={cn(disabled && "pointer-events-none opacity-50", className)} {...props} > {options.map((option, index) => { const checked = option.value === value; const iconOnly = !option.label; const tabbable = hasSelection ? checked : index === enabled[0]?.index; return ( <button key={option.value} ref={(node) => { refs.current[index] = node; }} type="button" role="radio" aria-checked={checked} aria-label={option["aria-label"]} data-slot="button" data-state={checked ? "on" : "off"} disabled={disabled || option.disabled} tabIndex={tabbable ? 0 : -1} onClick={() => select(option.value)} onKeyDown={(event) => onKeyDown(event, index)} className={cn( buttonVariants({ variant: "outline", size: iconOnly ? iconSizes[size] : size }), "text-muted-foreground hover:bg-accent/60 data-[state=on]:text-foreground dark:hover:bg-input/45", "data-[state=on]:hover:bg-transparent dark:data-[state=on]:hover:bg-input/30" )} > {checked && ( <motion.span aria-hidden layoutId="indicator" transition={reduceMotion ? { duration: 0 } : indicatorSpring} className="pointer-events-none absolute inset-0 rounded-[inherit] bg-white/[0.08] shadow-[inset_0_0_0_1px_rgb(255_255_255/0.12)]" /> )} <span className="relative z-[1] inline-flex items-center gap-2"> {option.icon} {option.label} </span> </button> ); })} </ButtonGroup> {name && <input type="hidden" name={name} value={value} />} </LayoutGroup> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| options | { value; label?; icon?; aria-label?; disabled? }[] | — | Segments. Icon-only segments need an aria-label. |
| value / onValueChange | string / (v: string) => void | — | Controlled value. |
| defaultValue | string | — | Uncontrolled initial value. Defaults to the first option. |
| size | "sm" | "default" | "lg" | "default" | Button size. |
| orientation | "horizontal" | "vertical" | "horizontal" | Layout and arrow-key axis. |
| name | string | — | Submit the value with a hidden input. |
Split Button
A primary action joined to a menu of alternatives. Picking another option makes it the main action: its label rolls in while the button springs to the new width, and the chevron flips while the menu is open.
"use client";
import * as React from "react";
import { GitMergeIcon, GitPullRequestArrowIcon, LayersIcon } from "lucide-react";
import { toast } from "sonner";
import { SplitButton } from "@/components/dusk/button-group/split-button";
const actions = [
{
value: "merge",
label: "Merge pull request",
description: "All commits are added to the base branch with a merge commit.",
icon: <GitMergeIcon />,
},
{
value: "squash",
label: "Squash and merge",
description: "The commits are combined into one commit on the base branch.",
icon: <LayersIcon />,
},
{
value: "rebase",
label: "Rebase and merge",
description: "The commits are rebased and added to the base branch.",
icon: <GitPullRequestArrowIcon />,
},
];
export default function SplitButtonDemo() {
const [loading, setLoading] = React.useState(false);
return (
<SplitButton
actions={actions}
loading={loading}
menuLabel="Choose a merge method"
onAction={(value) => {
setLoading(true);
setTimeout(() => {
setLoading(false);
toast.success(`${actions.find((a) => a.value === value)?.label} done`);
}, 900);
}}
/>
);
}$ npx shadcn@latest add https://duskui.com/r/split-button.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/button-group/split-button.tsx.split-button.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useReducedMotion, type Transition } from "motion/react"; import { ChevronDownIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import { ButtonGroup, ButtonGroupSeparator } from "@/components/ui/button-group"; import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; export interface SplitButtonAction { value: string; label: string; /** Shown under the label in the menu. */ description?: string; /** Leading icon element, shown on the button and in the menu. */ icon?: React.ReactNode; disabled?: boolean; } export interface SplitButtonProps { actions: SplitButtonAction[]; /** The action the main button runs (controlled). */ value?: string; defaultValue?: string; /** Fires when a different action is picked from the menu. */ onValueChange?: (value: string) => void; /** Fires when the main button is clicked, with the current action. */ onAction?: (value: string) => void; variant?: "default" | "secondary" | "outline"; size?: "sm" | "default" | "lg"; /** Spinner on the main button; the menu stays usable. */ loading?: boolean; disabled?: boolean; /** Accessible name of the menu button. */ menuLabel?: string; className?: string; } const swap: Transition = { type: "spring", duration: 0.35, bounce: 0 }; /** Tracks an element's width so a wrapper can spring to it. */ function useWidth(ref: React.RefObject<HTMLElement | null>) { const [width, setWidth] = React.useState<number | "auto">("auto"); React.useLayoutEffect(() => { const element = ref.current; if (!element) return; const observer = new ResizeObserver(([entry]) => { setWidth(entry.borderBoxSize?.[0]?.inlineSize ?? element.offsetWidth); }); observer.observe(element); return () => observer.disconnect(); }, [ref]); return width; } /** * A split button: a primary action joined to a menu of alternatives, like * "Merge pull request ▾". Picking another option makes it the main action — * its label rolls in while the button springs to the new width — and the * chevron flips while the menu is open. Built on the DuskUI Button, Button * Group and Dropdown Menu, so keyboard, focus and aria come from Radix. */ export function SplitButton({ actions, value: valueProp, defaultValue, onValueChange, onAction, variant = "default", size = "default", loading = false, disabled = false, menuLabel = "More options", className, }: SplitButtonProps) { const reduceMotion = useReducedMotion() ?? false; const [uncontrolled, setUncontrolled] = React.useState(defaultValue ?? actions[0]?.value ?? ""); const [open, setOpen] = React.useState(false); const value = valueProp ?? uncontrolled; const current = actions.find((action) => action.value === value) ?? actions[0]; const measureRef = React.useRef<HTMLSpanElement>(null); const width = useWidth(measureRef); const select = (next: string) => { if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }; const filled = variant !== "outline"; return ( <ButtonGroup className={className}> <Button variant={variant} size={size} loading={loading} disabled={disabled} onClick={() => current && onAction?.(current.value)} > <motion.span className="inline-flex overflow-hidden" initial={false} animate={{ width }} transition={reduceMotion ? { duration: 0 } : swap} > <span ref={measureRef} className="relative inline-flex items-center gap-2 whitespace-nowrap"> <AnimatePresence mode="popLayout" initial={false}> <motion.span key={current?.value} className="inline-flex items-center gap-2" initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -8 }} transition={swap} > {current?.icon} {current?.label} </motion.span> </AnimatePresence> </span> </motion.span> </Button> {filled && <ButtonGroupSeparator className="bg-black/25" />} <DropdownMenu open={open} onOpenChange={setOpen}> <DropdownMenuTrigger asChild> <Button variant={variant} size={size === "sm" ? "icon-sm" : size === "lg" ? "icon-lg" : "icon"} disabled={disabled} aria-label={menuLabel} > <ChevronDownIcon className={cn( "transition-transform duration-300 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none", open && "rotate-180" )} /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-64"> <DropdownMenuRadioGroup value={value} onValueChange={select}> {actions.map((action) => ( <DropdownMenuRadioItem key={action.value} value={action.value} disabled={action.disabled} className="items-start py-2" > <span className="grid gap-0.5"> <span className="flex items-center gap-2 font-medium"> {action.icon} {action.label} </span> {action.description && ( <span className="text-xs leading-snug text-muted-foreground">{action.description}</span> )} </span> </DropdownMenuRadioItem> ))} </DropdownMenuRadioGroup> </DropdownMenuContent> </DropdownMenu> </ButtonGroup> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| actions | { value; label; description?; icon?; disabled? }[] | — | The menu options. The selected one runs from the main button. |
| value / onValueChange | string / (v: string) => void | — | The selected action (controlled). |
| onAction | (value: string) => void | — | Main button click, with the selected action. |
| variant | "default" | "secondary" | "outline" | "default" | Button style. |
| loading | boolean | false | Spinner on the main button. |
| menuLabel | string | "More options" | Accessible name of the chevron button. |
API Reference
Each part accepts the props of the element it renders.
| Prop | Type | Default | Description |
|---|---|---|---|
| ButtonGroup orientation | "horizontal" | "vertical" | "horizontal" | Direction the segments join in. |
| ButtonGroupText asChild | boolean | false | Render your own element, e.g. a <label>. |
| ButtonGroupSeparator orientation | "vertical" | "horizontal" | "vertical" | Use horizontal inside vertical groups. |
Accessibility
ButtonGrouprendersrole="group"— give it anaria-labelthat names the set.- Focused segments rise above their neighbours, so focus rings are never clipped.
- The Animated Button Group is a
radiogroupwith roving tabindex and arrow-key selection. - The Split Button menu is a Radix Dropdown Menu with radio items, so it has full keyboard support and announces the checked option.
- Indicators and label rolls respect prefers-reduced-motion.