# Toggle
A button that stays pressed or unpressed.
Source page: https://dinachi.dev/docs/components/toggle

## Installation
```bash
npx @dinachi/cli@latest add toggle
```
Adds to your project:
- `components/ui/toggle/toggle.tsx`
- `components/ui/toggle/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `class-variance-authority` ^0.7.1

## Usage
```tsx
import { Toggle } from "@/components/ui/toggle"
import { Bold } from "lucide-react"

export function BoldToggle() {
  return (
    <Toggle aria-label="Toggle bold">
      <Bold className="h-4 w-4" />
    </Toggle>
  )
}
```

## Examples

### Default
An icon toggle for bold.
```tsx
import { Toggle } from '@/components/ui/toggle';
import { Bold } from 'lucide-react';

export function Example() {
  return (
    <Toggle aria-label="Toggle bold">
      <Bold className="h-4 w-4" />
    </Toggle>
  );
}
```

### Controlled
Pressed state held in React, with a live status.
```tsx
import React from 'react';
import { Toggle } from '@/components/ui/toggle';
import { Bold, Italic, Underline } from 'lucide-react';

export function Example() {
  const [formatting, setFormatting] = React.useState({
    bold: false,
    italic: false,
    underline: false
  });

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <Toggle
          pressed={formatting.bold}
          onPressedChange={(pressed) => setFormatting(prev => ({ ...prev, bold: pressed }))}
          aria-label="Toggle bold"
        >
          <Bold className="h-4 w-4" />
        </Toggle>
        <Toggle
          pressed={formatting.italic}
          onPressedChange={(pressed) => setFormatting(prev => ({ ...prev, italic: pressed }))}
          aria-label="Toggle italic"
        >
          <Italic className="h-4 w-4" />
        </Toggle>
        <Toggle
          pressed={formatting.underline}
          onPressedChange={(pressed) => setFormatting(prev => ({ ...prev, underline: pressed }))}
          aria-label="Toggle underline"
        >
          <Underline className="h-4 w-4" />
        </Toggle>
      </div>
      <div className="text-sm text-muted-foreground">
        Active: {Object.entries(formatting)
          .filter(([, active]) => active)
          .map(([format]) => format)
          .join(', ') || 'none'}
      </div>
    </div>
  );
}
```

### Variants
Default and outline.
```tsx
import { Toggle } from '@/components/ui/toggle';
import { Bold, Italic } from 'lucide-react';

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Toggle variant="default" aria-label="Bold">
        <Bold className="h-4 w-4" />
      </Toggle>
      <Toggle variant="outline" aria-label="Italic">
        <Italic className="h-4 w-4" />
      </Toggle>
    </div>
  );
}
```

### Sizes
Small, default and large.
```tsx
import { Toggle } from '@/components/ui/toggle';
import { Bold } from 'lucide-react';

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Toggle size="sm" aria-label="Small">
        <Bold className="h-3 w-3" />
      </Toggle>
      <Toggle size="default" aria-label="Default">
        <Bold className="h-4 w-4" />
      </Toggle>
      <Toggle size="lg" aria-label="Large">
        <Bold className="h-5 w-5" />
      </Toggle>
    </div>
  );
}
```

## Notes

### Several toggles
For a set, use [Toggle Group](/docs/components/toggle-group). It holds the shared value and agents read it as one control.

### toggleVariants
`toggleVariants` gives another element the same look.

## API reference
Props marked **agent** change what an agent reads or may do.

### Toggle
A two-state button.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `pressed` | `boolean` | - | Controlled pressed state. |
| `defaultPressed` | `boolean` | `false` | Starting state when uncontrolled. |
| `onPressedChange` **agent** | `(pressed, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `variant` | `"default" \| "outline"` | `"default"` | Outline adds a border. |
| `size` | `"default" \| "sm" \| "lg"` | `"default"` | Height and padding. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `value` | `string` | - | Identifies the toggle inside a `ToggleGroup`. |
| `render` | `ReactElement` | - | Swap the element, keep the behaviour. |

## Agent
Inside an `AgentProvider`, Toggle appears in `agent.snapshot()` as `toggle`.
Reads:
- `label`: The aria-label, or the button's text.
- `checked`: Whether it is pressed.
- `disabled`: True when the toggle is blocked.
Actions:
- `toggle()`: Flips the pressed state.
- `setChecked(true)`: Sets it pressed or unpressed. A no-op if already there.
An agent's change runs through `onPressedChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told the app refused. A disabled toggle refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "Toggle bold", action: "toggle" }],
})
```

## Accessibility
- Renders a `<button>` with aria-pressed.
- An icon-only toggle needs an aria-label. The agent reads the same name.
- Keep the label the same in both states; aria-pressed carries the state.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Flips the pressed state |

## Source
`components/ui/toggle/toggle.tsx`
```tsx
"use client"

import * as React from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { type VariantProps, cva } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { agentChecked, changeAsAgent, useAgentControl, useAgentState, useMergedRef } from "@/components/ui/agent"

const toggleVariants = cva(
  [
    "inline-flex items-center justify-center rounded-md text-sm font-medium",
    "ring-offset-background transition-colors duration-[var(--motion-duration-fast,150ms)]",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
    "disabled:pointer-events-none disabled:opacity-50",
    "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
    "data-[pressed]:bg-accent data-[pressed]:text-accent-foreground",
  ],
  {
    variants: {
      variant: {
        default: [
          "bg-transparent",
          "hover:bg-muted hover:text-muted-foreground",
          "data-[pressed]:hover:bg-accent/90",
          "data-[pressed]:data-[disabled]:bg-accent/50",
        ],
        outline: [
          "border border-input bg-transparent",
          "hover:bg-accent hover:text-accent-foreground hover:border-accent",
          "data-[pressed]:bg-accent data-[pressed]:text-accent-foreground data-[pressed]:border-accent",
          "data-[pressed]:hover:bg-accent/90",
          "data-[disabled]:border-input/50",
          "data-[pressed]:data-[disabled]:bg-accent/50 data-[pressed]:data-[disabled]:border-accent/50",
        ],
      },
      size: {
        default: "h-10 px-3",
        sm: "h-9 px-2.5 text-xs",
        lg: "h-11 px-5",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

export interface ToggleProps
  extends React.ComponentPropsWithoutRef<typeof TogglePrimitive>,
    VariantProps<typeof toggleVariants> {}

/**
 * Base UI's toggle, holding its own pressed state so an agent can press it the way a
 * parent would. Controlled use is unchanged, and `onPressedChange` sees the agent's
 * changes first and can cancel them. The agent reads pressed as `checked`.
 */
const Toggle = React.forwardRef<
  React.ComponentRef<typeof TogglePrimitive>,
  ToggleProps
>(({ className, variant, size, pressed: pressedProp, defaultPressed = false, onPressedChange, ...props }, ref) => {
  const [pressed, change] = useAgentState<boolean, TogglePrimitive.ChangeEventDetails>(
    pressedProp,
    defaultPressed,
    onPressedChange
  )
  const element = React.useRef<HTMLButtonElement | null>(null)
  const mergedRef = useMergedRef(ref, element)

  useAgentControl(() => {
    const set = (next: boolean) => (next === pressed ? undefined : changeAsAgent(change, next))
    return {
      kind: "toggle",
      element: element.current,
      checked: pressed,
      disabled: props.disabled,
      actions: {
        toggle: () => set(!pressed),
        setChecked: (value: unknown) => set(agentChecked(value)),
      },
    }
  })

  return (
    <TogglePrimitive
      ref={mergedRef}
      data-slot="toggle"
      className={cn(toggleVariants({ variant, size }), className)}
      {...props}
      pressed={pressed}
      onPressedChange={change}
    />
  )
})

Toggle.displayName = "Toggle"

export { Toggle, toggleVariants }
```
