Capítulo 36 de 43

Chapter 36: Toggle Group

Core Idea

A coordinated set of two-state buttons — supports both single-selection (radio-like) and multiple-selection modes, with roving-tabindex keyboard navigation between items.

Key Concepts

  • Anatomy: RootItem (one per button).
  • type ("single" | "multiple"): single mode's value is a string; multiple mode's value is a string[] — the type itself changes shape based on this prop.
  • rovingFocus (default true): whether Tab moves between items as one stop (roving tabindex) or each item gets its own tab stop.
  • Ensuring a value always exists: in single mode, controlling value/onValueChange and rejecting empty-value changes (only updating state when the new value is truthy) is the documented pattern for a toggle group that must always have one item selected — Radix doesn't enforce "always one selected" itself.

Code Examples

const [value, setValue] = React.useState("left");

<ToggleGroup.Root
  type="single"
  value={value}
  onValueChange={(v) => { if (v) setValue(v); }}
>
  <ToggleGroup.Item value="left">Left</ToggleGroup.Item>
  <ToggleGroup.Item value="center">Center</ToggleGroup.Item>
  <ToggleGroup.Item value="right">Right</ToggleGroup.Item>
</ToggleGroup.Root>
  • What it demonstrates: the "always one value selected" pattern — ignore the value-change callback's falsy case (clicking the already-active item) instead of letting it clear the selection.

Key Takeaways

  1. Reach for type="single" as a segmented-control alternative to RadioGroup when you want button styling instead of radio dots; type="multiple" for independent-but-grouped toggles (e.g. text formatting: bold/italic/underline together).
  2. Radix does not force single-mode to always have a selection — implement that constraint yourself in onValueChange if required, as shown above.
  3. rovingFocus follows the same roving-tabindex convention as RadioGroup/Tabs — disable it only if you specifically need every item individually tabbable.

Connects To

  • Toggle: the single-button building block this composes.
  • Radio Group: the semantically-different (native radio-role) alternative for single-selection.