# Toggle Group

A row of toggle buttons where one or several stay pressed.

A row of Toggles where one stays pressed (text alignment, a view) or, multiple, several (bold, italic, underline). Each item is the Toggle: the same looks, sizes, shapes, square and muted, the same pressed fill; icon-only items are named and tipped by their labels (a Tooltip). One tab stop, arrow keys move between the items, Space / Enter press. Unlike the segmented control there is no track and no sliding thumb, and nothing has to be pressed. Behaviour by Ark UI's toggle-group (Zag). Controlled or uncontrolled.

Kind: component · Category: Actions · Status: beta · Targets: React, Vue, Svelte · Behaviour: Zag `toggle-group` machine, through Ark UI

## Add

```bash
npx fndn add toggle-group
```

It writes the folder `toggle-group/` into the project's ui folder (`index.ts`, `toggle-group.tsx`, `ToggleGroup.vue`, `ToggleGroup.svelte`, `toggle-group.recipe.ts`), and what it is built from: [Toggle](/components/toggle.md), [Tooltip](/components/tooltip.md), [Button Group](/components/button-group.md). First time: [Installation](/installation.md).

## Usage

```tsx
import { ToggleGroup } from "@/components/ui/toggle-group";
```

```vue
import { ToggleGroup } from "@/components/ui/toggle-group";
```

```svelte
import { ToggleGroup } from "$lib/components/ui/toggle-group";
```

## Parts

In the DOM the root carries `data-slot="toggle-group"` and each part `data-slot="toggle-group-<part>"`; in the recipe the root is the `base` slot and each part a slot named after it in camelCase.

| Part | Element | data-slot | Flags | Notes |
| --- | --- | --- | --- | --- |
| `root` | `div` | `toggle-group` |  | Ark's toggle-group root: role=radiogroup when one at most, role=group with multiple. Outline items are joined into one control, as a button group joins Buttons: square inner corners, one hairline at each join; a press dims the pressed item and moves nothing. Ghost (borderless) items sit 2px apart. It wraps rather than overflowing. Vertical: a column of full-width items, their content at the start. |
| `item` | `button` | `toggle-group-item` | repeats | One Toggle (the toggle recipe's classes): role=radio with aria-checked when one at most, aria-pressed with multiple (styled from those: a Tooltip around an icon-only item writes its own data-state on it). Pressed: hover-2, hovered or not; muted turns ink. Only one item is in the tab order. |
| `icon` | `span` | `toggle-group-icon` | optional | The Toggle's icon part; aria-hidden. |
| `label` | `span` | `toggle-group-label` | optional | The Toggle's label part: cut at the end with a title when the item has less room. Not shown on a square item that has an icon: its label is then its aria-label and its tooltip. A square item without an icon shows its (short) label and is named by its tooltip when it has one. |

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `{ value: string; label?: string; tooltip?: string; disabled?: boolean }[]` |  | The toggles, in order. Strings are accepted as value = label. Each may carry an icon (a node in React). |
| `value` | `string[]` | `[]` | Bindable (React: `defaultValue` and `onValueChange`; Vue: `v-model:value`; Svelte: `bind:value`). The pressed values. |
| `multiple` | `boolean` | `false` | Several may be pressed at once. Otherwise one at most. |
| `deselectable` | `boolean` | `true` | One at most: a click on the pressed item releases it. false keeps one pressed once chosen. |
| `variant` | `"outline" \| "ghost"` | `"outline"` | The Toggle's looks. |
| `size` | `"xs" \| "sm" \| "md" \| "lg"` | `"md"` | The Toggle's sizes. The one control height scale: xs 24px, sm 28px, md 32px, lg 36px (an sm Toggle lines up with an sm Button or Select). Dimensions only, as the Button. |
| `shape` | `"pill" \| "rounded"` |  | The shape of the toggles, as on Toggle. Left out, the app's shape: a pill, or rounded in a rounded app ("shape": "rounded" in the project's fndn.json). |
| `square` | `boolean` | `false` | Icon-only items, as wide as they are tall; each label names its item and is its tooltip. |
| `muted` | `boolean` | `false` | Quiet at rest, ink when hovered, held down or pressed: ink-3 for icon-only items (square), ink-2 for items with a label. |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | vertical: a column; Arrow Up / Down move. |
| `disabled` | `boolean` | `false` |  |

Other attributes and `class` go to the root; `class` is merged through the recipe.

## Events

| Event | Payload |
| --- | --- |
| `valueChange` | (value: string[]) after a click, Space or Enter |

## States

`pressed`, `hover`, `press`, `focus-visible`, `disabled`

## Keyboard and accessibility

Role: radiogroup of radios while one at most can be pressed; group of toggle buttons (aria-pressed) with multiple.

Keyboard:

- Tab moves into the group (to the last focused item) and out of it
- Arrow Right / Arrow Left (vertical: Arrow Down / Arrow Up) move to the next / previous item, wrapping; mirrored right-to-left
- Home / End: the first / last item
- Space / Enter press or release the focused item

Notes:

- One at most: role=radiogroup with role=radio items and aria-checked. Multiple: role=group with toggle buttons and aria-pressed.
- Name the group with aria-label. Icon-only items are named by their labels (aria-label), which their Tooltips show.
- To set it from outside, control `value`: React value / onValueChange.

## Motion

- the Toggle's: press scales to motion.press-scale; hover fill and colour over duration.fast (pointer only)
- pressed fill: over duration.fast from a pointer; instant from the keyboard (kbd-instant)
- focus moves between the items instantly

## Tokens

`color.ink`, `color.hover-2`

## Dependencies

- [Toggle](/components/toggle.md)
- [Tooltip](/components/tooltip.md)
- [Button Group](/components/button-group.md)

## Examples

### Text formatting toolbar

React · `text-formatting.tsx`

```tsx
import { useState } from "react";
import { TextB, TextItalic, TextUnderline } from "@phosphor-icons/react";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* several at once: bold, italic and underline apply together */
const styles = [
  { value: "bold", label: "Bold", icon: <TextB data-slot="icon" weight="bold" /> },
  { value: "italic", label: "Italic", icon: <TextItalic data-slot="icon" weight="bold" /> },
  { value: "underline", label: "Underline", icon: <TextUnderline data-slot="icon" weight="bold" /> },
];

export default function TextFormatting() {
  const [format, setFormat] = useState<string[]>(["bold"]);
  return (
    <div className="flex w-80 flex-col gap-3">
      <ToggleGroup aria-label="Text style" multiple size="sm" value={format} onValueChange={setFormat} items={styles} />
      <p
        className="text-sm text-ink-2"
        style={{
          fontWeight: format.includes("bold") ? 600 : undefined,
          fontStyle: format.includes("italic") ? "italic" : undefined,
          textDecoration: format.includes("underline") ? "underline" : undefined,
        }}
      >
        Webhook deliveries now retry for up to 24 hours.
      </p>
    </div>
  );
}
```

Vue · `text-formatting.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { PhTextB, PhTextItalic, PhTextUnderline } from "@phosphor-icons/vue";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* several at once: bold, italic and underline apply together */
const styles = [
  { value: "bold", label: "Bold", icon: PhTextB },
  { value: "italic", label: "Italic", icon: PhTextItalic },
  { value: "underline", label: "Underline", icon: PhTextUnderline },
];

const format = ref<string[]>(["bold"]);
</script>

<template>
  <div class="flex w-80 flex-col gap-3">
    <ToggleGroup v-model:value="format" aria-label="Text style" multiple size="sm" :items="styles" />
    <p
      class="text-sm text-ink-2"
      :style="{
        fontWeight: format.includes('bold') ? 600 : undefined,
        fontStyle: format.includes('italic') ? 'italic' : undefined,
        textDecoration: format.includes('underline') ? 'underline' : undefined,
      }"
    >
      Webhook deliveries now retry for up to 24 hours.
    </p>
  </div>
</template>
```

Svelte · `text-formatting.svelte`

```svelte
<script lang="ts">
  import TextB from "phosphor-svelte/lib/TextBIcon";
  import TextItalic from "phosphor-svelte/lib/TextItalicIcon";
  import TextUnderline from "phosphor-svelte/lib/TextUnderlineIcon";
  import { ToggleGroup } from "$lib/components/ui/toggle-group";

  /* several at once: bold, italic and underline apply together */
  const styles = [
    { value: "bold", label: "Bold", icon: TextB },
    { value: "italic", label: "Italic", icon: TextItalic },
    { value: "underline", label: "Underline", icon: TextUnderline },
  ];

  let format = $state<string[]>(["bold"]);
</script>

<div class="flex w-80 flex-col gap-3">
  <ToggleGroup bind:value={format} aria-label="Text style" multiple size="sm" items={styles} />
  <p
    class="text-sm text-ink-2"
    style:font-weight={format.includes("bold") ? 600 : undefined}
    style:font-style={format.includes("italic") ? "italic" : undefined}
    style:text-decoration={format.includes("underline") ? "underline" : undefined}
  >
    Webhook deliveries now retry for up to 24 hours.
  </p>
</div>
```

### Text alignment, icon-only

React · `alignment.tsx`

```tsx
import { TextAlignCenter, TextAlignLeft, TextAlignRight } from "@phosphor-icons/react";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* one at most, never none: alignment always has a value; icon-only items are named by their labels */
const alignments = [
  { value: "left", label: "Align left", icon: <TextAlignLeft data-slot="icon" weight="bold" /> },
  { value: "center", label: "Align center", icon: <TextAlignCenter data-slot="icon" weight="bold" /> },
  { value: "right", label: "Align right", icon: <TextAlignRight data-slot="icon" weight="bold" /> },
];

export default function Alignment() {
  return (
    <ToggleGroup
      aria-label="Alignment"
      variant="ghost"
      size="sm"
      shape="rounded"
      square
      muted
      deselectable={false}
      defaultValue={["left"]}
      items={alignments}
    />
  );
}
```

Vue · `alignment.vue`

```vue
<script setup lang="ts">
import { PhTextAlignCenter, PhTextAlignLeft, PhTextAlignRight } from "@phosphor-icons/vue";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* one at most, never none: alignment always has a value; icon-only items are named by their labels */
const alignments = [
  { value: "left", label: "Align left", icon: PhTextAlignLeft },
  { value: "center", label: "Align center", icon: PhTextAlignCenter },
  { value: "right", label: "Align right", icon: PhTextAlignRight },
];
</script>

<template>
  <ToggleGroup
    aria-label="Alignment"
    variant="ghost"
    size="sm"
    shape="rounded"
    square
    muted
    :deselectable="false"
    :value="['left']"
    :items="alignments"
  />
</template>
```

Svelte · `alignment.svelte`

```svelte
<script lang="ts">
  import TextAlignCenter from "phosphor-svelte/lib/TextAlignCenterIcon";
  import TextAlignLeft from "phosphor-svelte/lib/TextAlignLeftIcon";
  import TextAlignRight from "phosphor-svelte/lib/TextAlignRightIcon";
  import { ToggleGroup } from "$lib/components/ui/toggle-group";

  /* one at most, never none: alignment always has a value; icon-only items are named by their labels */
  const alignments = [
    { value: "left", label: "Align left", icon: TextAlignLeft },
    { value: "center", label: "Align center", icon: TextAlignCenter },
    { value: "right", label: "Align right", icon: TextAlignRight },
  ];
</script>

<ToggleGroup
  aria-label="Alignment"
  variant="ghost"
  size="sm"
  shape="rounded"
  square
  muted
  deselectable={false}
  value={["left"]}
  items={alignments}
/>
```

### Filter pull requests

React · `pull-request-filter.tsx`

```tsx
import { useState } from "react";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* one at most, and a second click clears it: a filter you can switch off */
const COUNTS: Record<string, number> = { open: 12, merged: 15, closed: 4 };
const states = [
  { value: "open", label: "Open" },
  { value: "merged", label: "Merged" },
  { value: "closed", label: "Closed" },
];

export default function PullRequestFilter() {
  const [show, setShow] = useState<string[]>(["open"]);
  const state = show[0];
  return (
    <div className="flex flex-col items-start gap-2">
      <ToggleGroup aria-label="Show pull requests" size="sm" value={show} onValueChange={setShow} items={states} />
      <p className="text-sm text-ink-2" role="status">
        {state ? `${COUNTS[state]} ${state} pull requests in billing-api` : "All 31 pull requests in billing-api"}
      </p>
    </div>
  );
}
```

Vue · `pull-request-filter.vue`

```vue
<script setup lang="ts">
import { computed, ref } from "vue";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* one at most, and a second click clears it: a filter you can switch off */
const COUNTS: Record<string, number> = { open: 12, merged: 15, closed: 4 };
const states = [
  { value: "open", label: "Open" },
  { value: "merged", label: "Merged" },
  { value: "closed", label: "Closed" },
];

const show = ref<string[]>(["open"]);
const state = computed(() => show.value[0]);
</script>

<template>
  <div class="flex flex-col items-start gap-2">
    <ToggleGroup v-model:value="show" aria-label="Show pull requests" size="sm" :items="states" />
    <p class="text-sm text-ink-2" role="status">
      {{ state ? `${COUNTS[state]} ${state} pull requests in billing-api` : "All 31 pull requests in billing-api" }}
    </p>
  </div>
</template>
```

Svelte · `pull-request-filter.svelte`

```svelte
<script lang="ts">
  import { ToggleGroup } from "$lib/components/ui/toggle-group";

  /* one at most, and a second click clears it: a filter you can switch off */
  const COUNTS: Record<string, number> = { open: 12, merged: 15, closed: 4 };
  const states = [
    { value: "open", label: "Open" },
    { value: "merged", label: "Merged" },
    { value: "closed", label: "Closed" },
  ];

  let show = $state<string[]>(["open"]);
  const shown = $derived(show[0]);
</script>

<div class="flex flex-col items-start gap-2">
  <ToggleGroup bind:value={show} aria-label="Show pull requests" size="sm" items={states} />
  <p class="text-sm text-ink-2" role="status">
    {shown ? `${COUNTS[shown]} ${shown} pull requests in billing-api` : "All 31 pull requests in billing-api"}
  </p>
</div>
```

### Notification channels, one not on your plan

React · `notify-channels.tsx`

```tsx
import { Bell, DeviceMobile, EnvelopeSimple } from "@phosphor-icons/react";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* several channels at once; one the plan does not include is disabled and says why */
const channels = [
  { value: "email", label: "Email", icon: <EnvelopeSimple data-slot="icon" weight="bold" /> },
  { value: "in-app", label: "In app", icon: <Bell data-slot="icon" weight="bold" /> },
  { value: "sms", label: "SMS", icon: <DeviceMobile data-slot="icon" weight="bold" />, tooltip: "SMS alerts need the Business plan", disabled: true },
];

export default function NotifyChannels() {
  return (
    <div className="flex flex-col items-start gap-2">
      <p className="text-sm font-medium text-ink">When a deploy fails, notify me by</p>
      <ToggleGroup aria-label="When a deploy fails, notify me by" multiple size="sm" defaultValue={["email", "in-app"]} items={channels} />
    </div>
  );
}
```

Vue · `notify-channels.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { PhBell, PhDeviceMobile, PhEnvelopeSimple } from "@phosphor-icons/vue";
import { ToggleGroup } from "@/components/ui/toggle-group";

/* several channels at once; one the plan does not include is disabled and says why */
const channels = [
  { value: "email", label: "Email", icon: PhEnvelopeSimple },
  { value: "in-app", label: "In app", icon: PhBell },
  { value: "sms", label: "SMS", icon: PhDeviceMobile, tooltip: "SMS alerts need the Business plan", disabled: true },
];

const notify = ref<string[]>(["email", "in-app"]);
</script>

<template>
  <div class="flex flex-col items-start gap-2">
    <p class="text-sm font-medium text-ink">When a deploy fails, notify me by</p>
    <ToggleGroup v-model:value="notify" aria-label="When a deploy fails, notify me by" multiple size="sm" :items="channels" />
  </div>
</template>
```

Svelte · `notify-channels.svelte`

```svelte
<script lang="ts">
  import Bell from "phosphor-svelte/lib/BellIcon";
  import DeviceMobile from "phosphor-svelte/lib/DeviceMobileIcon";
  import EnvelopeSimple from "phosphor-svelte/lib/EnvelopeSimpleIcon";
  import { ToggleGroup } from "$lib/components/ui/toggle-group";

  /* several channels at once; one the plan does not include is disabled and says why */
  const channels = [
    { value: "email", label: "Email", icon: EnvelopeSimple },
    { value: "in-app", label: "In app", icon: Bell },
    { value: "sms", label: "SMS", icon: DeviceMobile, tooltip: "SMS alerts need the Business plan", disabled: true },
  ];

  let notify = $state<string[]>(["email", "in-app"]);
</script>

<div class="flex flex-col items-start gap-2">
  <p class="text-sm font-medium text-ink">When a deploy fails, notify me by</p>
  <ToggleGroup bind:value={notify} aria-label="When a deploy fails, notify me by" multiple size="sm" items={channels} />
</div>
```

## Recipe

`toggle-group.recipe.ts`:

```ts
import { tv, type VariantProps } from "../lib/tv";
import { buttonGroup } from "../button-group/button-group.recipe";

/* toggle-group — a row of Toggles where one (or, multiple, several) stay pressed: text alignment,
 * bold / italic / underline, a view filter (Ark UI toggle-group: one tab stop, arrow keys move).
 *
 * Each item is the Toggle: the adapter gives it the toggle recipe's classes (sizes, shapes, square,
 * muted, the pressed fill, the press scale, kbd-instant), and this recipe only adds what a group
 * needs. In single mode the engine marks an item as a radio (aria-checked) rather than a toggle
 * button (aria-pressed), so the pressed look is repeated for aria-checked here, hovered or not.
 *
 * Two looks. ghost: borderless items 2px apart, as the Toggles of a toolbar are. outline: the
 * outlined items are joined into one control, exactly as a button group joins Buttons (its recipe,
 * composed: inner corners square, one hairline at each join, a focused item above its
 * neighbours), because outlined pills a hair apart read as a control that came apart.
 * Joined, an item never scales (a join would
 * open); its label and icon dip inside the still box instead, as in a button group. A vertical group stacks them at full width.
 * Styled from aria-*, never data-state: a Tooltip around an icon-only item writes its own
 * data-state on the same element. */
/* the button group's joins, for the outline look */
const JOIN = "[&>[data-slot=toggle-group-item]:active]:[transform:none]! [&>[data-slot=toggle-group-item]>*]:motion-transform-press [:root:not([data-fndn-input=keyboard])_&>[data-slot=toggle-group-item]:active>*]:scale-press-sm";

export const toggleGroup = tv({
  slots: {
    base: "inline-flex max-w-full min-w-0 items-center gap-0.5 outline-none",
    item: "aria-checked:bg-hover-2 aria-checked:hover:bg-hover-2",
    /* the Toggle's icon and label parts */
    icon: "",
    label: "",
  },
  variants: {
    orientation: {
      horizontal: { base: "flex-wrap" },
      vertical: { base: "flex-col items-stretch", item: "justify-start" },
    },
    muted: {
      true: { item: "aria-checked:text-ink" },
    },
    variant: { outline: {}, ghost: {} },
  },
  compoundVariants: [
    { variant: "outline", orientation: "horizontal", class: { base: [buttonGroup({ orientation: "horizontal" }).base(), JOIN, "gap-0 flex-wrap"] } },
    { variant: "outline", orientation: "vertical", class: { base: [buttonGroup({ orientation: "vertical" }).base(), JOIN, "gap-0"] } },
  ],
  defaultVariants: { orientation: "horizontal", muted: false, variant: "outline" },
});

export type ToggleGroupRecipeProps = VariantProps<typeof toggleGroup>;
```
