Toggle
A pressable button that switches between two visual or functional states. Commonly used for formatting or mode selection.
Code
Installation
Toggle component:
npx shadcn@latest add toggleToggle Group component:
npx shadcn@latest add toggle-groupBasic Example
import { Toggle } from "@/components/ui/toggle"
const [pressed, setPressed] = useState(false)
<Toggle
pressed={pressed}
onPressedChange={setPressed}
>
Italic
</Toggle>Toggle Group
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
<ToggleGroup type="multiple">
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
<ToggleGroupItem value="underline">Underline</ToggleGroupItem>
</ToggleGroup>Reference
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| pressed | boolean | — | Controlled pressed state (Toggle) |
| onPressedChange | function | — | Callback when pressed state changes (Toggle) |
| type | string | — | Toggle group type. Options: single, multiple (ToggleGroup) |
| size | string | "default" | Size variant. Options: sm, default, lg, icon |
States
Toggle Group
Usage Guidelines
When to Use
Use toggle buttons for binary states that can be turned on or off. They work well for formatting controls, filters, and settings. Use toggle groups when you have related options that can be selected independently (multiple) or exclusively (single).
Toggle buttons are ideal for toolbar controls and inline formatting options. Toggle groups work well for filter sets and option selections where multiple items can be active.
Best Practices
- Use clear visual distinction between pressed and unpressed states
- Group related toggles together visually
- Use icons for space-constrained contexts
- Provide aria-label for icon-only toggles
- Use toggle groups for related options
Accessibility
Toggle buttons are fully keyboard accessible. Users can activate with Space or Enter. Always provide aria-label attributes for icon-only toggles. The pressed state is automatically communicated to screen readers.
For toggle groups, ensure each item has a unique value and proper labels. Use type="single" for mutually exclusive options and type="multiple" for independent selections.