Toggle
A two-state button that can be either on or off.
Overview
The Toggle component is a two-state button that can be either on or off. It's commonly used for enabling or disabling options, showing or hiding UI elements, or toggling between two states.
Our Toggle component is built with Radix UI primitives and follows WAI-ARIA best practices. It supports keyboard navigation, focus management, and screen reader announcements.
Basic Usage
The default Toggle component provides a simple, accessible toggle button.
Examples
With Text
Toggle with text for better clarity.
Toggle Group
Group multiple toggles together for related options.
Disabled State
Toggle can be disabled to prevent user interaction.
Variants
Toggle comes with different variants to match your design needs.
Sizes
Toggle comes in different sizes to fit your UI needs.
Text Alignment
Example of using toggles for text alignment options.
API Reference
The Toggle component provides a way to switch between two states.
| Prop | Type | Description |
|---|---|---|
| pressed | boolean | Whether the toggle is pressed or not. Use with onPressedChange for controlled usage. |
| defaultPressed | boolean | The default state of the toggle when initially rendered. Use for uncontrolled usage. |
| onPressedChange | function | Event handler called when the pressed state changes. |
| disabled | boolean | When true, prevents the user from interacting with the toggle. |
| variant | "default" | "outline" | The visual style of the toggle. |
| size | "sm" | "default" | "lg" | The size of the toggle. |
| asChild | boolean | When true, the component will render its child as the toggle. |
The Toggle component also accepts all standard HTML attributes for the button element.
Usage Guidelines
Follow these guidelines for effective use of the Toggle component:
Best Practices
Do
- Use toggles for binary states (on/off, enabled/disabled)
- Group related toggles together
- Use clear icons or labels to indicate the toggle's purpose
- Provide immediate visual feedback when the state changes
- Use aria-label for icon-only toggles
Don't
- Use toggles for actions that should be buttons
- Use toggles for mutually exclusive options (use radio buttons instead)
- Use toggles without clear indication of their purpose
- Place toggles too close together, making them difficult to select
- Use toggles for complex state changes that aren't immediately visible
Accessibility
The Toggle component follows WAI-ARIA guidelines to ensure accessibility.
Keyboard Navigation
Users can navigate to toggles using the Tab key and toggle them using the Space key.
Screen Readers
The component uses proper ARIA attributes to communicate state changes to assistive technologies.
Accessibility Tip
Always provide an aria-label for icon-only toggles to ensure screen reader users understand their purpose. For toggles with visible text, the text content will be used as the accessible name.