toggle.tsx

Overview

The toggle.tsx file defines a reusable, customizable toggle button component for React applications. It leverages the @radix-ui/react-toggle primitive for accessible toggle behavior and enhances it with styling variants using the class-variance-authority (CVA) library. The component supports multiple visual variants and sizes, allowing consistent styling across the application with ease.

This file is designed to be a UI building block, enabling toggling states (on/off) with built-in accessibility and keyboard support, while also providing flexible styling through variant props.


Detailed Documentation

Dependencies


toggleVariants (constant)

A CVA instance defining the styling variants for the Toggle component.

Usage example:

const className = toggleVariants({ variant: 'outline', size: 'lg' });
// returns the combined class string for outlined large toggle

Toggle Component

A React functional component that wraps TogglePrimitive.Root from Radix UI with additional styling and variant support.

Signature

function Toggle({
  className,
  variant,
  size,
  ...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
  VariantProps<typeof toggleVariants>)

Parameters

Returns

Behavior & Features

Usage Example

import { Toggle } from './toggle';

function Example() {
  const [pressed, setPressed] = React.useState(false);

  return (
    <Toggle
      pressed={pressed}
      onPressedChange={setPressed}
      variant="outline"
      size="lg"
      aria-label="Toggle dark mode"
    >
      Dark Mode
    </Toggle>
  );
}

Implementation Details


Integration with the System


Diagram: Component Structure and Interaction

componentDiagram
    component Toggle
    component TogglePrimitive.Root
    component cn (class merging utility)
    component toggleVariants (cva styling generator)

    Toggle --> TogglePrimitive.Root : wraps
    Toggle --> toggleVariants : uses for classNames
    Toggle --> cn : merges classNames

    note right of TogglePrimitive.Root
      Provides:
      - Accessibility\n
      - Toggle behavior\n
      - State management
    end

Summary

The toggle.tsx file provides a styled, accessible toggle button component built on Radix UI's toggle primitive and enhanced with flexible variants via CVA. It offers multiple size and style variants, seamless integration with SVG icons, and supports all standard toggle props. This component serves as a foundational interactive element for toggling states in the wider React application.