usmds docs

Toggle

Toggle is a switch that allows users to turn a setting on or off.

Installation

npx usmds add toggle

Usage

import { Toggle } from '@components/Toggle';
import { useState } from 'react';
 
function App() {
  const [pressed, setPressed] = useState(false);
  
  return (
    <Toggle 
      pressed={pressed} 
      onPressedChange={setPressed} 
    />
  );
}

Props

Toggle

Extends TogglePrimitive.Root props.

PropTypeDefaultDescription
pressedbooleanfalseThe controlled pressed state of the toggle.
onPressedChange(pressed: boolean) => void-Callback when pressed state changes.
disabledbooleanfalseWhen true, prevents user interaction.
classNamestring-Additional Tailwind classes to apply.

Examples

Basic Usage

function ToggleExample() {
  const [pressed, setPressed] = useState(false);
  return (
    <Toggle 
      pressed={pressed} 
      onPressedChange={setPressed} 
    />
  );
}

Disabled State

function DisabledToggle() {
  const [pressed, setPressed] = useState(false);
  return (
    <Toggle 
      pressed={pressed} 
      onPressedChange={setPressed} 
      disabled 
    />
  );
}

Styling

The Toggle component uses Tailwind CSS classes for styling through class-variance-authority (cva). Default styling includes:

  • Container dimensions: 51px × 31px
  • Knob dimensions: 27px × 27px
  • Rounded full corners
  • Primary color when on
  • Cool gray color when off
  • White knob color
  • Consistent knob positioning:
    • On: 22px from left
    • Off: 2px from left
  • Disabled state opacity: 50%

States

The toggle has several visual states:

  • Off: Cool gray background with left-aligned knob
  • On: Primary color background with right-aligned knob
  • Disabled: Reduced opacity with left-aligned knob

Accessibility

The Toggle component:

  • Uses accessibilityRole="switch" for proper semantic structure
  • Provides appropriate accessibilityState for checked and disabled states
  • Supports keyboard navigation
  • Maintains WCAG color contrast requirements
  • Uses adequate touch target size (31px height)

On this page