toggle-group.tsx


Overview

The toggle-group.tsx file defines a reusable and customizable Toggle Group React component built on top of the @radix-ui/react-toggle-group primitives. This component provides a grouped toggle button interface supporting multiple styling variants and sizes, facilitating consistent UI controls in applications.

The file exports two main components:

These components leverage React context to share styling variants and sizes between the group and its items, ensuring consistent appearance and behavior. The use of class-variance-authority for managing variants combined with utility CSS classes enables flexible styling.


Components and Functions

1. ToggleGroup

Description

The ToggleGroup component acts as a wrapper for one or more ToggleGroupItem components. It manages the overall styling, variant, and size context for its children toggle items.

Props

Returns

A styled ToggleGroupPrimitive.Root component wrapping the children and providing a React context with the variant and size values.

Usage Example

<ToggleGroup type="single" variant="outline" size="sm" defaultValue="left">
  <ToggleGroupItem value="left">Left</ToggleGroupItem>
  <ToggleGroupItem value="center">Center</ToggleGroupItem>
  <ToggleGroupItem value="right">Right</ToggleGroupItem>
</ToggleGroup>

2. ToggleGroupItem

Description

Represents an individual toggle button inside the ToggleGroup. It consumes the variant and size from the nearest ToggleGroup context but can also accept its own variant and size props to override the context.

Props

Returns

A styled ToggleGroupPrimitive.Item component interacting with the toggle group.

Usage Example

<ToggleGroupItem value="bold">Bold</ToggleGroupItem>

When used inside a ToggleGroup, it automatically receives the variant and size unless explicitly overridden.


Implementation Details


Interaction with the System


Mermaid Diagram

classDiagram
    class ToggleGroup {
        +props: ToggleGroupPrimitive.Root props & VariantProps
        +render()
    }
    class ToggleGroupItem {
        +props: ToggleGroupPrimitive.Item props & VariantProps
        +render()
    }
    class ToggleGroupContext {
        +variant: string
        +size: string
    }

    ToggleGroup "1" --> "many" ToggleGroupItem : provides context
    ToggleGroup ..> ToggleGroupContext : uses React context
    ToggleGroupItem ..> ToggleGroupContext : consumes context

Summary

This file provides a composable and stylable toggle group UI component with tightly integrated variant and size management through React context. Leveraging Radix UI primitives ensures accessibility and consistent toggle group behavior, while the use of class-variance-authority and a utility class merging function allow flexible styling. It fits into a UI component ecosystem as a building block for toggle controls with customizable appearances.