Toggle Group
A set of toggles that work together, for choosing one option or several from a short row.
Installation
pnpm dlx shadcn@latest add @silkware/toggle-groupTo copy the component by hand, install its dependencies:
pnpm add react-aria-components class-variance-authority cnThen copy the source into components/ui/toggle-group.tsx. It also needs Toggle, for the shared styles:
"use client"
import * as React from "react"import { type VariantProps } from "class-variance-authority"import { cn } from "cn"import { ToggleButtonGroup as ToggleGroupPrimitive, ToggleButton as TogglePrimitive, type ToggleButtonGroupProps, type ToggleButtonProps,} from "@animate-ui/react/primitives/react-aria"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext< VariantProps<typeof toggleVariants> & { spacing?: number orientation?: "horizontal" | "vertical" }>({ size: "default", variant: "default", spacing: 2, orientation: "horizontal",})
function ToggleGroup({ className, variant, size, spacing = 2, orientation = "horizontal", children, ...props}: Omit<ToggleButtonGroupProps, "children"> & VariantProps<typeof toggleVariants> & { spacing?: number orientation?: "horizontal" | "vertical" children?: React.ReactNode }) { return ( <ToggleGroupPrimitive data-slot="toggle-group" data-variant={variant} data-size={size} data-spacing={spacing} orientation={orientation} style={ { "--gap": `calc(var(--spacing) * ${spacing})` } as React.CSSProperties } className={cn( "group/toggle-group flex w-fit flex-row items-center gap-(--gap) rounded-md data-[spacing=0]:data-[variant=outline]:shadow-xs data-vertical:flex-col data-vertical:items-stretch", className )} {...props} > <ToggleGroupContext.Provider value={{ variant, size, spacing, orientation }} > {children} </ToggleGroupContext.Provider> </ToggleGroupPrimitive> )}
function ToggleGroupItem({ className, children, variant = "default", size = "default", ...props}: ToggleButtonProps & VariantProps<typeof toggleVariants>) { const context = React.useContext(ToggleGroupContext)
return ( <TogglePrimitive data-slot="toggle-group-item" data-variant={context.variant || variant} data-size={context.size || size} data-spacing={context.spacing} className={cn( "shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 group-data-[spacing=0]/toggle-group:shadow-none focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-md group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-md group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-md group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-md data-[state=on]:bg-muted group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t", toggleVariants({ variant: context.variant || variant, size: context.size || size, }), className )} {...props} > {children} </TogglePrimitive> )}
export { ToggleGroup, ToggleGroupItem }Usage
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"<ToggleGroup aria-label="Report period" selectionMode="single" defaultSelectedKeys={["week"]} variant="outline"> <ToggleGroupItem id="day">Day</ToggleGroupItem> <ToggleGroupItem id="week">Week</ToggleGroupItem> <ToggleGroupItem id="month">Month</ToggleGroupItem></ToggleGroup>Every item needs an id. The group reports the selection as a set of ids through onSelectionChange, and takes selectedKeys or defaultSelectedKeys as an array of ids. The group sets variant and size for all its items, so set them on the group and not on each item.
The default selectionMode is "single", and people can press the selected item again to clear it. Add disallowEmptySelection when one option must always be chosen.
Examples
Multiple selection
selectionMode="multiple" lets each item switch on and off independently, like a row of filters.
Variant
The default variant has no border and suits toolbars. outline draws a border around each item, and with spacing={0} it draws one around the whole group.
Size
sm, default and lg apply to every item in the group.
Spacing
spacing is the gap between items in steps of 0.25rem. The default is 2. At 0 the items join into one segmented control with shared edges.
Vertical
orientation="vertical" stacks the items and makes them fill the width. Use it in a narrow panel or a sidebar.
Disabled
isDisabled on the group disables every item. isDisabled on one item disables only that item.
Controlled
Use selectedKeys and onSelectionChange when the selection drives something else on the page. onSelectionChange receives a Set of ids.
Showing the report by week
Accessibility
| Key | Action |
|---|---|
| Tab | Moves focus into the group, to the item focused last or else the first item, and then out of it. |
| ArrowRight | Moves focus to the next item in a horizontal group. |
| ArrowLeft | Moves focus to the previous item in a horizontal group. |
| ArrowDown | Moves focus to the next item in a vertical group. |
| ArrowUp | Moves focus to the previous item in a vertical group. |
| Space | Toggles the focused item. |
| Enter | Toggles the focused item. |
React Aria provides:
- A
radiogroupfor single selection and atoolbarfor multiple selection, withradioitems that reportaria-checkedin the first case andaria-pressedbuttons in the second. - Roving focus: the group is one stop in the tab order, and arrow keys move between items.
- The selection model, including
disallowEmptySelectionand disabled items.
You provide:
- An
aria-labeloraria-labelledbyon the group that names what is being chosen. - Visible text, or an
aria-label, on every item. - A visible selected state that does not rely on colour alone. The default fill is soft, so prefer the
outlinevariant when the group stands alone.
Guidelines
When to use
- To choose one option from a short set that people compare at a glance, such as day, week or month.
- To switch several filters on and off, such as order statuses.
- To pick a view mode in a toolbar, such as list or grid.
When not to use
- For a single on and off option. Use a Toggle.
- For options in a form that need a description each. Use a Radio Group.
- For more than about five options, or long labels. Use a Select.
- To switch between panels of content. Use Tabs.
- For related actions that are not on or off. Use a Button Group.
Content
- Keep labels to one word or a short phrase, in sentence case: "Week", "Late orders".
- Make the labels the same kind of thing: all periods, or all statuses.
- Use icons only for options with a well-known symbol, and give each an
aria-label.
Number of options
Use a group for three or four short options, and keep one chosen with disallowEmptySelection.
Don’t line up a long list of options. The row wraps and people cannot compare them. Use a select.
API reference
ToggleGroup
Renders a <div> through the React Aria ToggleButtonGroup. It accepts every prop of it and the props below.
| Prop | Type | Default | Description |
|---|---|---|---|
selectionMode? | "single" | "multiple" | "single" | Whether one item or several can be on at once. |
selectedKeys? | Iterable<Key> | None | The ids that are on, for a controlled group. |
defaultSelectedKeys? | Iterable<Key> | None | The ids that start on, for an uncontrolled group. |
onSelectionChange? | (keys: Set<Key>) => void | None | Called with the new set of ids when the selection changes. |
disallowEmptySelection? | boolean | false | Prevents clearing the last selected item. |
variant? | "default" | "outline" | "default" | Applies to every item. |
size? | "sm" | "default" | "lg" | "default" | Applies to every item. |
spacing? | number | 2 | The gap between items, in steps of 0.25rem. At 0 the items join. |
orientation? | "horizontal" | "vertical" | "horizontal" | The direction of the row, which also sets the arrow keys. |
isDisabled? | boolean | false | Disables every item. |
aria-label? | string | None | The accessible name of the group. |
ToggleGroupItem
One option. It renders a React Aria ToggleButton with the toggle styles. variant and size are taken from the group when it sets them.
| Prop | Type | Default | Description |
|---|---|---|---|
id? | Key | None | The value of the item. It is what selectedKeys and onSelectionChange use, so set it on every item. |
isDisabled? | boolean | false | Disables only this item. |
aria-label? | string | None | The accessible name, required when the item has no visible text. |