suiss/ui
  • Docs
  • Components
  • Patterns
  • Interactions
  • Charts
  • Blocks
  • AI
GitHubCreate
DocsComponentsPatternsInteractionsChartsBlocksAICreate
Components84
  • Overview
  • Accordion
  • Alert
  • Alert Dialog
  • Alert Sheet
  • Amount Input
  • Aspect Ratio
  • Attachment
  • Avatar
  • Badge
  • Bottom Bar
  • Breadcrumb
  • Bubble
  • Button
  • Button Group
  • Calendar
  • Card
  • Carousel
  • Chart
  • Checkbox
  • Chip
  • Code Block
  • Collapsible
  • Combobox
  • Command
  • Context Menu
  • Dialog
  • Direction
  • Drawer
  • Dropdown Menu
  • Empty
  • FAB
  • Field
  • Fullscreen Menu
  • Haptics
  • Header
  • Hover Card
  • Icon
  • Input
  • Input Accessory Bar
  • Input Group
  • Input OTP
  • Item
  • Kbd
  • Keyboard Scroll View
  • Keypad
  • Label
  • Marker
  • Menubar
  • Message
  • Message Scroller
  • Native Select
  • Navigation Menu
  • Page Indicator
  • Pagination
  • Pin Pad
  • Popover
  • Progress
  • QR Scanner
  • Questionnaire
  • Radio Group
  • Resizable
  • Screen
  • Scroll Area
  • Select
  • Separator
  • Sheet
  • Sidebar
  • Signature Pad
  • Skeleton
  • Slider
  • Spinner
  • Switch
  • Tab Bar
  • Table
  • Tabs
  • Text
  • Textarea
  • Toast
  • Toggle
  • Toggle Group
  • Tooltip
  • Trace
  • Wheel Picker
  • Widget

suiss/ui · Component

Toggle

A two-state button that stays pressed until it's pressed again.

Toggle is an open-source component from suiss/ui for React, React Native, SwiftUI and Jetpack Compose. The @esuiss/ui CLI copies its source into your project, so you own the code.

import { TextBIcon } from "@phosphor-icons/react"
import { Toggle } from "@/components/ui/toggle"

export default function ToggleDemo() {
  return (
    <Toggle aria-label="Toggle bold">
      <TextBIcon />
    </Toggle>
  )
}

Toggle wraps the toggle primitive of the chosen base. When pressed, it shows a tinted background and primary-colored content, and it scales down slightly while being pressed.

Use a toggle for a single on-off option such as bold text or a bookmark. To choose among related options, use ToggleGroup; for a setting that takes effect immediately, use Switch.

Installation

$ pnpm dlx shadcn@latest add @esuiss/toggle

Works in any project with a components.json. See Installation for the one-line registry setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add toggle
  1. Install the following dependencies and add the cn helper:
$ pnpm add @base-ui/react class-variance-authority
  1. Copy and paste the following code into your project.
components/ui/toggle.tsx
"use client"

import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"

const toggleVariants = cva(
  "gap-1 rounded-lg text-sm transition-[color,background-color,scale] duration-200 ease-[cubic-bezier(0.3,1.25,0.5,1)] active:scale-96 motion-reduce:active:scale-100 hover:bg-accent hover:text-accent-foreground focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-pressed:bg-accent aria-pressed:text-[color-mix(in_oklab,var(--primary)_80%,var(--foreground))] aria-pressed:hover:bg-accent aria-pressed:hover:text-[color-mix(in_oklab,var(--primary)_80%,var(--foreground))] inline-flex items-center justify-center whitespace-nowrap outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 disabled:opacity-50 group/toggle [&_svg:not([class*='size-'])]:size-4",
  {
    variants: {
      variant: {
        default: "bg-transparent",
        outline: "border border-border bg-transparent hover:bg-accent hover:text-accent-foreground",
      },
      size: {
        default: "h-9 min-w-9 px-3 has-data-[icon=inline-end]:pe-2.5 has-data-[icon=inline-start]:ps-2.5",
  1. Update the import paths to match your project setup.

Usage

import { Toggle } from "@/components/ui/toggle"
<Toggle aria-label="Toggle bold">
  <TextBIcon />
</Toggle>

Examples

Pressed

Set defaultPressed to start the toggle in the pressed state.

Set defaultSelected to start the toggle in the pressed state.

import { TextBIcon } from "@phosphor-icons/react"
import { Toggle } from "@/components/ui/toggle"

export default function TogglePressed() {
  return (
    <Toggle aria-label="Toggle bold" defaultPressed>
      <TextBIcon />
    </Toggle>
  )
}

Variants

Use the variant prop to switch between the borderless default style and the outline style with a border.

import { TextBIcon } from "@phosphor-icons/react"
import { Toggle } from "@/components/ui/toggle"

export default function ToggleVariants() {
  return (
    <div className="flex items-center gap-3">
      <Toggle aria-label="Toggle bold" variant="default">
        <TextBIcon />
      </Toggle>
      <Toggle aria-label="Toggle bold" variant="outline">
        <TextBIcon />
      </Toggle>
    </div>
  )
}

Sizes

Use the size prop to set the height and padding: sm, default or lg.

import { TextBIcon } from "@phosphor-icons/react"
import { Toggle } from "@/components/ui/toggle"

export default function ToggleSizes() {
  return (
    <div className="flex items-center gap-3">
      <Toggle aria-label="Toggle bold" size="sm">
        <TextBIcon />
      </Toggle>
      <Toggle aria-label="Toggle bold" size="default">
        <TextBIcon />
      </Toggle>
      <Toggle aria-label="Toggle bold" size="lg">
        <TextBIcon />
      </Toggle>
    </div>

With text

Pairs an icon with a text label. Mark the icon with data-icon="inline-start" or data-icon="inline-end" to tighten the padding on that side.

import { BookmarkSimpleIcon, TextItalicIcon } from "@phosphor-icons/react"
import { Toggle } from "@/components/ui/toggle"

export default function ToggleWithText() {
  return (
    <div className="flex items-center gap-3">
      <Toggle aria-label="Toggle italic">
        <TextItalicIcon data-icon="inline-start" />
        Italic
      </Toggle>
      <Toggle variant="outline" aria-label="Save for later">
        <BookmarkSimpleIcon data-icon="inline-start" />
        Save
      </Toggle>
    </div>
  )

Disabled

Set disabled so the toggle ignores clicks and keyboard presses.

Set isDisabled so the toggle ignores clicks and keyboard presses.

import { TextBIcon } from "@phosphor-icons/react"
import { Toggle } from "@/components/ui/toggle"

export default function ToggleDisabled() {
  return (
    <Toggle disabled aria-label="Toggle bold">
      <TextBIcon />
    </Toggle>
  )
}

Accessibility

  • Renders a button with aria-pressed reflecting its state.
  • Enter and Space toggle the focused button.
  • An icon-only toggle needs an aria-label.

API Reference

Toggle

The pressable two-state button.

PropTypeDefault
variant"default" | "outline""default"
size"default" | "sm" | "lg""default"
pressedboolean—
defaultPressedbooleanfalse
onPressedChange(pressed: boolean) => void—
disabledbooleanfalse
PropTypeDefault
variant"default" | "outline""default"
size"default" | "sm" | "lg""default"
isSelectedboolean—
defaultSelectedbooleanfalse
onChange(isSelected: boolean) => void—
isDisabledbooleanfalse

Also accepts the props of the primitive part it wraps.

Use defaultPressed for an uncontrolled toggle, or pressed with onPressedChange to control it. The toggle sets data-slot="toggle", and its pressed styles key off aria-pressed.

Use defaultSelected for an uncontrolled toggle, or isSelected with onChange to control it. The toggle sets data-slot="toggle", and its pressed styles key off data-selected.

toggleVariants is exported so other components, such as ToggleGroupItem, can share the styles. The press animation is removed when reduced motion is preferred.

Web

Web preview

import { TextBIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleDemoExample() {
  const [pressed, setPressed] = React.useState(false)
  return (
    <View className="flex-row">
      <Toggle
        pressed={pressed}
        onPressedChange={setPressed}
        accessibilityLabel="Toggle bold"
      >
        <ToggleIcon as={TextBIcon} />
      </Toggle>
import { TextBIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleDemoExample() {
  const [pressed, setPressed] = React.useState(false)
  return (
    <View style={{ flexDirection: "row" }}>
      <Toggle
        pressed={pressed}
        onPressedChange={setPressed}
        accessibilityLabel="Toggle bold"
      >
        <ToggleIcon as={TextBIcon} />
      </Toggle>
import PhosphorSwift
import SwiftUI

struct ToggleExample: View {
  var body: some View {
    ToggleDemo(label: "Toggle bold") { Ph.textB.regular }
  }
}

struct ToggleDemo<Icon: View>: View {
  let variant: ToggleVariant
  let size: ToggleSize
  let label: LocalizedStringKey
  let icon: Icon

  @State private var isOn: Bool
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.TextB

Toggle is a Pressable with an on and off state. When on, it shows a selected background and its text turns to the primary color; it scales down slightly while pressed. It has two variants, default and outline, and three sizes.

ToggleIcon is an Icon sized for use inside a toggle.

Installation

$ pnpm dlx shadcn@latest add @esuiss/toggle

See Installation for the components.json setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add toggle
$ pnpm dlx shadcn@latest add @esuiss/toggle

See Installation for the components.json setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add toggle --platform swift
$ pnpm dlx shadcn@latest add @esuiss/toggle

See Installation for the components.json setup. Or use the suiss/ui CLI:

$ pnpm dlx @esuiss/ui@latest add toggle --platform kotlin

The CLI also adds what it builds on: Icon, Text.

  1. Install the following dependencies:
npx expo install class-variance-authority cn
  1. Add the pieces it builds on: Icon, Text.

  2. Copy the primitives it uses into components/primitives:

uniwind/components/primitives/event-details.ts
import type { HostInstance } from "react-native"
import type {
  BaseUIChangeEventDetails,
  BaseUIGenericEventDetails,
  ChangeEvent,
} from "./types"

const REASONS = {
  none: "none",
  triggerPress: "trigger-press",
  triggerLongPress: "trigger-long-press",
  outsidePress: "outside-press",
  itemPress: "item-press",
  closePress: "close-press",
  backPress: "back-press",
  accessibilityEscape: "accessibility-escape",
uniwind/components/primitives/haptics.tsx
import * as React from "react"

type HapticsImpactStyle = "light" | "medium" | "heavy" | "soft" | "rigid"

type HapticsNotificationType = "success" | "warning" | "error"

interface HapticsAdapter {
  impact(style: HapticsImpactStyle): void
  selection(): void
  notification(type: HapticsNotificationType): void
}

interface HapticsContextValue {
  adapter: HapticsAdapter | null
  enabled: boolean
}
uniwind/components/primitives/hooks.ts
import * as React from "react"
import { BackHandler } from "react-native"

function useEffectEvent<TArgs extends readonly unknown[], TResult>(
  callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
  const callbackRef = React.useRef(callback)

  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })

  return React.useCallback(
    (...args: TArgs): TResult => callbackRef.current(...args),
    []
  )
uniwind/components/primitives/merge-props.ts
type AnyProps = Record<string, unknown>

type PropsGetter = (previous: AnyProps) => object

type MergePropsInput = object | PropsGetter | null | undefined

type Handler = (...args: unknown[]) => unknown

type StyleCallback = (state: never) => unknown

const EMPTY_PROPS: AnyProps = {}

function isEventHandler(key: string, value: unknown) {
  const code0 = key.charCodeAt(0)
  const code1 = key.charCodeAt(1)
  const code2 = key.charCodeAt(2)
uniwind/components/primitives/toggle-group.tsx
import * as React from "react"
import { type LayoutRectangle, View } from "react-native"
import type { REASONS } from "./event-details"
import type {
  BaseUIChangeEventDetails,
  BaseUIComponentProps,
  Orientation,
} from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ToggleGroupChangeEventReason =
  | typeof REASONS.itemPress
  | typeof REASONS.none

type ToggleGroupChangeEventDetails =
uniwind/components/primitives/toggle.tsx
import * as React from "react"
import {
  type GestureResponderEvent,
  type LayoutChangeEvent,
  type LayoutRectangle,
  Pressable,
  type View,
} from "react-native"
import { createChangeEventDetails, REASONS } from "./event-details"
import { useHaptics } from "./haptics"
import { useToggleGroupContext } from "./toggle-group"
import type { BaseUIChangeEventDetails, BaseUIComponentProps } from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ToggleChangeEventReason =
uniwind/components/primitives/types.ts
import type * as React from "react"
import type {
  GestureResponderEvent,
  HostInstance,
  NativeSyntheticEvent,
  StyleProp,
  ViewStyle,
} from "react-native"

type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"

type ComponentRenderFn<Props, State> = (
  props: Props,
  state: State
uniwind/components/primitives/use-controllable-state.ts
import * as React from "react"
import { useEffectEvent } from "./hooks"
import type { BaseUIChangeEventDetails } from "./types"

interface CancelableDetails {
  readonly isCanceled: boolean
}

interface UseControllableStateParameters<
  T,
  Details extends CancelableDetails = BaseUIChangeEventDetails,
> {
  value?: T | undefined
  defaultValue: T
  onChange?: ((value: T, details: Details) => void) | undefined
}
uniwind/components/primitives/use-render.tsx
import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"

type AnyProps = Record<string, unknown>

type RefInput<T> = React.Ref<T> | undefined

interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
  defaultComponent?: React.ElementType | undefined
  render?: RenderProp<Props, State> | undefined
  props?: object | readonly (object | null | undefined)[] | undefined
  state?: State | undefined
  ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
  className?: ClassNameProp<State>
  1. Copy and paste the following code into components/ui/toggle.tsx:
uniwind/components/ui/toggle.tsx
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Pressable } from "react-native"
import {
  Toggle as TogglePrimitive,
  type ToggleState,
} from "@/components/primitives/toggle"
import { resolveClassName } from "@/components/primitives/use-render"
import { Icon } from "@/components/ui/icon"
import { TextClassContext } from "@/components/ui/text"

const toggleVariants = cva(
  "flex-row items-center justify-center gap-1 rounded-toggle",
  {
    variants: {
      variant: {
  1. Update the import paths to match your project setup.
  1. Install the following dependencies:
npx expo install class-variance-authority cn
  1. Add the pieces it builds on: Icon, Text.

  2. Copy the primitives it uses into components/primitives:

nativewind/components/primitives/event-details.ts
import type { HostInstance } from "react-native"
import type {
  BaseUIChangeEventDetails,
  BaseUIGenericEventDetails,
  ChangeEvent,
} from "./types"

const REASONS = {
  none: "none",
  triggerPress: "trigger-press",
  triggerLongPress: "trigger-long-press",
  outsidePress: "outside-press",
  itemPress: "item-press",
  closePress: "close-press",
  backPress: "back-press",
  accessibilityEscape: "accessibility-escape",
nativewind/components/primitives/haptics.tsx
import * as React from "react"

type HapticsImpactStyle = "light" | "medium" | "heavy" | "soft" | "rigid"

type HapticsNotificationType = "success" | "warning" | "error"

interface HapticsAdapter {
  impact(style: HapticsImpactStyle): void
  selection(): void
  notification(type: HapticsNotificationType): void
}

interface HapticsContextValue {
  adapter: HapticsAdapter | null
  enabled: boolean
}
nativewind/components/primitives/hooks.ts
import * as React from "react"
import { BackHandler } from "react-native"

function useEffectEvent<TArgs extends readonly unknown[], TResult>(
  callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
  const callbackRef = React.useRef(callback)

  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })

  return React.useCallback(
    (...args: TArgs): TResult => callbackRef.current(...args),
    []
  )
nativewind/components/primitives/merge-props.ts
type AnyProps = Record<string, unknown>

type PropsGetter = (previous: AnyProps) => object

type MergePropsInput = object | PropsGetter | null | undefined

type Handler = (...args: unknown[]) => unknown

type StyleCallback = (state: never) => unknown

const EMPTY_PROPS: AnyProps = {}

function isEventHandler(key: string, value: unknown) {
  const code0 = key.charCodeAt(0)
  const code1 = key.charCodeAt(1)
  const code2 = key.charCodeAt(2)
nativewind/components/primitives/toggle-group.tsx
import * as React from "react"
import { type LayoutRectangle, View } from "react-native"
import type { REASONS } from "./event-details"
import type {
  BaseUIChangeEventDetails,
  BaseUIComponentProps,
  Orientation,
} from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ToggleGroupChangeEventReason =
  | typeof REASONS.itemPress
  | typeof REASONS.none

type ToggleGroupChangeEventDetails =
nativewind/components/primitives/toggle.tsx
import * as React from "react"
import {
  type GestureResponderEvent,
  type LayoutChangeEvent,
  type LayoutRectangle,
  Pressable,
  type View,
} from "react-native"
import { createChangeEventDetails, REASONS } from "./event-details"
import { useHaptics } from "./haptics"
import { useToggleGroupContext } from "./toggle-group"
import type { BaseUIChangeEventDetails, BaseUIComponentProps } from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ToggleChangeEventReason =
nativewind/components/primitives/types.ts
import type * as React from "react"
import type {
  GestureResponderEvent,
  HostInstance,
  NativeSyntheticEvent,
  StyleProp,
  ViewStyle,
} from "react-native"

type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"

type ComponentRenderFn<Props, State> = (
  props: Props,
  state: State
nativewind/components/primitives/use-controllable-state.ts
import * as React from "react"
import { useEffectEvent } from "./hooks"
import type { BaseUIChangeEventDetails } from "./types"

interface CancelableDetails {
  readonly isCanceled: boolean
}

interface UseControllableStateParameters<
  T,
  Details extends CancelableDetails = BaseUIChangeEventDetails,
> {
  value?: T | undefined
  defaultValue: T
  onChange?: ((value: T, details: Details) => void) | undefined
}
nativewind/components/primitives/use-render.tsx
import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"

type AnyProps = Record<string, unknown>

type RefInput<T> = React.Ref<T> | undefined

interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
  defaultComponent?: React.ElementType | undefined
  render?: RenderProp<Props, State> | undefined
  props?: object | readonly (object | null | undefined)[] | undefined
  state?: State | undefined
  ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
  className?: ClassNameProp<State>
  1. Copy and paste the following code into components/ui/toggle.tsx:
nativewind/components/ui/toggle.tsx
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Pressable } from "react-native"
import {
  Toggle as TogglePrimitive,
  type ToggleState,
} from "@/components/primitives/toggle"
import { resolveClassName } from "@/components/primitives/use-render"
import { Icon } from "@/components/ui/icon"
import { TextClassContext } from "@/components/ui/text"

const toggleVariants = cva(
  "flex-row items-center justify-center gap-1 rounded-toggle",
  {
    variants: {
      variant: {
  1. Update the import paths to match your project setup.
  1. Add the pieces it builds on: Icon, Text.

  2. Copy the primitives it uses into components/primitives:

stylesheet/components/primitives/event-details.ts
import type { HostInstance } from "react-native"
import type {
  BaseUIChangeEventDetails,
  BaseUIGenericEventDetails,
  ChangeEvent,
} from "./types"

const REASONS = {
  none: "none",
  triggerPress: "trigger-press",
  triggerLongPress: "trigger-long-press",
  outsidePress: "outside-press",
  itemPress: "item-press",
  closePress: "close-press",
  backPress: "back-press",
  accessibilityEscape: "accessibility-escape",
stylesheet/components/primitives/haptics.tsx
import * as React from "react"

type HapticsImpactStyle = "light" | "medium" | "heavy" | "soft" | "rigid"

type HapticsNotificationType = "success" | "warning" | "error"

interface HapticsAdapter {
  impact(style: HapticsImpactStyle): void
  selection(): void
  notification(type: HapticsNotificationType): void
}

interface HapticsContextValue {
  adapter: HapticsAdapter | null
  enabled: boolean
}
stylesheet/components/primitives/hooks.ts
import * as React from "react"
import { BackHandler } from "react-native"

function useEffectEvent<TArgs extends readonly unknown[], TResult>(
  callback: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
  const callbackRef = React.useRef(callback)

  React.useLayoutEffect(() => {
    callbackRef.current = callback
  })

  return React.useCallback(
    (...args: TArgs): TResult => callbackRef.current(...args),
    []
  )
stylesheet/components/primitives/merge-props.ts
type AnyProps = Record<string, unknown>

type PropsGetter = (previous: AnyProps) => object

type MergePropsInput = object | PropsGetter | null | undefined

type Handler = (...args: unknown[]) => unknown

type StyleCallback = (state: never) => unknown

const EMPTY_PROPS: AnyProps = {}

function isEventHandler(key: string, value: unknown) {
  const code0 = key.charCodeAt(0)
  const code1 = key.charCodeAt(1)
  const code2 = key.charCodeAt(2)
stylesheet/components/primitives/toggle-group.tsx
import * as React from "react"
import { type LayoutRectangle, View } from "react-native"
import type { REASONS } from "./event-details"
import type {
  BaseUIChangeEventDetails,
  BaseUIComponentProps,
  Orientation,
} from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ToggleGroupChangeEventReason =
  | typeof REASONS.itemPress
  | typeof REASONS.none

type ToggleGroupChangeEventDetails =
stylesheet/components/primitives/toggle.tsx
import * as React from "react"
import {
  type GestureResponderEvent,
  type LayoutChangeEvent,
  type LayoutRectangle,
  Pressable,
  type View,
} from "react-native"
import { createChangeEventDetails, REASONS } from "./event-details"
import { useHaptics } from "./haptics"
import { useToggleGroupContext } from "./toggle-group"
import type { BaseUIChangeEventDetails, BaseUIComponentProps } from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ToggleChangeEventReason =
stylesheet/components/primitives/types.ts
import type * as React from "react"
import type {
  GestureResponderEvent,
  HostInstance,
  NativeSyntheticEvent,
  StyleProp,
  ViewStyle,
} from "react-native"

type Side = "top" | "bottom" | "left" | "right"
type Align = "start" | "center" | "end"
type Orientation = "horizontal" | "vertical"

type ComponentRenderFn<Props, State> = (
  props: Props,
  state: State
stylesheet/components/primitives/use-controllable-state.ts
import * as React from "react"
import { useEffectEvent } from "./hooks"
import type { BaseUIChangeEventDetails } from "./types"

interface CancelableDetails {
  readonly isCanceled: boolean
}

interface UseControllableStateParameters<
  T,
  Details extends CancelableDetails = BaseUIChangeEventDetails,
> {
  value?: T | undefined
  defaultValue: T
  onChange?: ((value: T, details: Details) => void) | undefined
}
stylesheet/components/primitives/use-render.tsx
import * as React from "react"
import { useComposedRefs } from "./hooks"
import { mergeClassNames, mergeProps, mergeStyles } from "./merge-props"
import type { ClassNameProp, RenderProp, StyleValue } from "./types"

type AnyProps = Record<string, unknown>

type RefInput<T> = React.Ref<T> | undefined

interface UseRenderParameters<State, RefType = unknown, Props = AnyProps> {
  defaultComponent?: React.ElementType | undefined
  render?: RenderProp<Props, State> | undefined
  props?: object | readonly (object | null | undefined)[] | undefined
  state?: State | undefined
  ref?: RefInput<RefType> | readonly RefInput<RefType>[] | undefined
  className?: ClassNameProp<State>
  1. Copy and paste the following code into components/ui/toggle.tsx:
stylesheet/components/ui/toggle.tsx
import type * as React from "react"
import {
  Pressable,
  type StyleProp,
  StyleSheet,
  type TextStyle,
  type ViewStyle,
} from "react-native"
import {
  Toggle as TogglePrimitive,
  type ToggleState,
} from "@/components/primitives/toggle"
import { resolveStyle } from "@/components/primitives/use-render"
import { Icon } from "@/components/ui/icon"
import { TextStyleContext } from "@/components/ui/text"
import {
  1. Update the import paths to match your project setup.
  1. Target iOS 17 or later.

  2. Add the Swift package to your app:

Package.swift
.package(url: "https://github.com/phosphor-icons/swift", from: "2.1.0")
  1. Copy the theme files every view uses:
swift/Theme/Theme.swift
import CoreText
import SwiftUI
import UIKit

struct RGBA: Sendable {
  let red: CGFloat
  let green: CGFloat
  let blue: CGFloat
  let alpha: CGFloat

  init(_ hex: UInt32, _ alpha: CGFloat = 1) {
    red = CGFloat((hex >> 16) & 0xFF) / 255
    green = CGFloat((hex >> 8) & 0xFF) / 255
    blue = CGFloat(hex & 0xFF) / 255
    self.alpha = alpha
  }
swift/Theme/Tokens.swift
import SwiftUI

public enum EsuissColor {
  public static let background = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
  public static let foreground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let card = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
  public static let cardForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let popover = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
  public static let popoverForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let primary = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0A84FF))
  public static let primaryForeground = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
  public static let secondary = Color.adaptive(light: .init(0x000000, 0.04), dark: .init(0xFFFFFF, 0.1))
  public static let secondaryForeground = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let muted = Color.adaptive(light: .init(0xF5F5F7), dark: .init(0x161617))
  public static let mutedForeground = Color.adaptive(light: .init(0x6E6E73), dark: .init(0x86868B))
  public static let accent = Color.adaptive(light: .init(0x000000, 0.06), dark: .init(0xFFFFFF, 0.1))
  1. Copy the source and every file it uses:
swift/Components/Toggle.swift
import SwiftUI

public enum ToggleVariant: CaseIterable, Sendable {
  case `default`, outline
}

public enum ToggleSize: CaseIterable, Sendable {
  case `default`, sm, lg

  var height: CGFloat {
    switch self {
    case .default: 36
    case .sm: 32
    case .lg: 40
    }
  }
swift/Components/Button.swift
import SwiftUI

public struct VariantButtonStyle: ButtonStyle {
  public enum Variant: CaseIterable, Sendable {
    case `default`, outline, secondary, tinted, ghost, plain, destructive, link
  }

  public enum Size: CaseIterable, Sendable {
    case `default`, xs, sm, lg, xl, form, icon, iconXs, iconSm, iconLg, iconXl

    var height: CGFloat {
      switch self {
      case .xs, .iconXs: Metrics.Height.buttonXs
      case .sm, .iconSm: Metrics.Height.buttonSm
      case .default, .icon: Metrics.Height.button
      case .lg, .iconLg: Metrics.Height.buttonLg
swift/Components/ButtonGroup.swift
import SwiftUI

extension EnvironmentValues {
  @Entry var buttonGroup: Axis? = nil
  @Entry var buttonGroupSize: CGSize = .zero
}

enum ButtonGroupSpace: Hashable {
  case group
}

struct ButtonGroupFrame {
  let bounds: Anchor<CGRect>
  let outlined: Bool
}
swift/Components/Checkbox.swift
import PhosphorSwift
import SwiftUI

extension Shadow {
  static let control = Shadow(color: .black.opacity(0.08), radius: 0.5, y: 0.5)
  static let thumb = Shadow(color: .black.opacity(0.12), radius: 1.5, y: 1)
}

struct SelectionIndicator<Mark: View>: View {
  let checked: Bool
  let pressed: Bool
  let cornerRadius: CGFloat
  let mark: Mark

  @Environment(\.isEnabled) private var isEnabled
  @Environment(\.isInvalid) private var invalid
swift/Components/Field.swift
import SwiftUI

extension EnvironmentValues {
  @Entry public var isInvalid = false
  @Entry var fieldInset = false
  @Entry var fieldSize = FieldSize.default
  @Entry var fieldGroupInset = false
  @Entry var fieldSetInset = false
}

extension View {
  public func invalid(_ isInvalid: Bool = true) -> some View {
    environment(\.isInvalid, isInvalid)
  }
}
swift/Components/Haptics.swift
import SwiftUI

extension EnvironmentValues {
  @Entry public var hapticsEnabled = true
}

extension View {
  public func haptics(_ enabled: Bool) -> some View {
    environment(\.hapticsEnabled, enabled)
  }

  func hapticFeedback<Trigger: Equatable>(_ feedback: SensoryFeedback, trigger: Trigger) -> some View {
    modifier(HapticFeedbackModifier(feedback: feedback, trigger: trigger) { _, _ in true })
  }

  func hapticFeedback<Trigger: Equatable>(
swift/Components/Separator.swift
import SwiftUI

public struct Separator: View {
  let orientation: Axis

  public init(_ orientation: Axis = .horizontal) {
    self.orientation = orientation
  }

  public var body: some View {
    Rectangle()
      .fill(EsuissColor.border)
      .frame(width: orientation == .vertical ? 1 : nil, height: orientation == .horizontal ? 1 : nil)
      .frame(maxWidth: orientation == .horizontal ? .infinity : nil, maxHeight: orientation == .vertical ? .infinity : nil)
      .accessibilityHidden(true)
  }
  1. Add the files to your app target.
  1. Apply the Compose compiler plugin, enable Compose, set compileSdk to 37 or higher and minSdk to 24 or higher, and add the dependencies:
build.gradle.kts
plugins {
    id("org.jetbrains.kotlin.plugin.compose")
}

android {
    compileSdk = 37
    defaultConfig { minSdk = 24 }
    buildFeatures { compose = true }
}

dependencies {
    implementation(platform("androidx.compose:compose-bom:2026.09.00"))
    implementation("androidx.compose.foundation:foundation")
    implementation("androidx.compose.ui:ui")
    implementation("com.adamglin:phosphor-icon-android:1.0.0")
}
  1. Copy the theme files every view uses:
kotlin/theme/Theme.kt
package com.esuiss.ui.theme

import android.content.res.AssetManager
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.dropShadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.shadow.Shadow as DropShadow
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
kotlin/theme/Tokens.kt
package com.esuiss.ui.theme

import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

@Immutable
data class Colors(
    val background: Color,
    val foreground: Color,
    val card: Color,
    val cardForeground: Color,
    val popover: Color,
    val popoverForeground: Color,
    val primary: Color,
  1. Copy the source and every file it uses:
kotlin/components/Toggle.kt
package com.esuiss.ui.components

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
kotlin/components/Checkbox.kt
package com.esuiss.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.triStateToggleable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
kotlin/components/Content.kt
package com.esuiss.ui.components

import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

val LocalContentStyle = compositionLocalOf { TextStyle.Default }

val LocalContentColor = compositionLocalOf { Color.Unspecified }

val LocalIconSize = compositionLocalOf { 20.dp }
kotlin/components/Field.kt
package com.esuiss.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.LayoutScopeMarker
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
kotlin/components/FormSupport.kt
package com.esuiss.ui.components

import android.provider.Settings
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
kotlin/components/Haptics.kt
package com.esuiss.ui.components

import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback

val LocalHapticsEnabled = staticCompositionLocalOf { true }

@Composable
fun ProvideHaptics(enabled: Boolean, content: @Composable () -> Unit) {
    CompositionLocalProvider(LocalHapticsEnabled provides enabled, content = content)
}
kotlin/components/Icon.kt
package com.esuiss.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import com.esuiss.ui.theme.EsuissTheme

@Composable
fun Icon(
    imageVector: ImageVector,
kotlin/components/Label.kt
package com.esuiss.ui.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography
kotlin/components/Separator.kt
package com.esuiss.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.EsuissTheme

@Composable
fun Separator(
  1. Update the com.esuiss.ui package names to match your project.

Usage

import { TextBIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

type ToggleDemoProps = Omit<
  React.ComponentProps<typeof Toggle>,
  "pressed" | "onPressedChange"
> & {
  initial?: boolean
}

function ToggleDemo({ initial = false, children, ...props }: ToggleDemoProps) {
  const [pressed, setPressed] = React.useState(initial)
  return (
    <Toggle pressed={pressed} onPressedChange={setPressed} {...props}>
      {children}
    </Toggle>
  )
}

export function ToggleExample() {
  return (
    <View className="flex-row">
      <ToggleDemo accessibilityLabel="Toggle bold">
        <ToggleIcon as={TextBIcon} />
      </ToggleDemo>
    </View>
  )
}
import { TextBIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

type ToggleDemoProps = Omit<
  React.ComponentProps<typeof Toggle>,
  "pressed" | "onPressedChange"
> & {
  initial?: boolean
}

function ToggleDemo({ initial = false, children, ...props }: ToggleDemoProps) {
  const [pressed, setPressed] = React.useState(initial)
  return (
    <Toggle pressed={pressed} onPressedChange={setPressed} {...props}>
      {children}
    </Toggle>
  )
}

export function ToggleExample() {
  return (
    <View style={{ flexDirection: "row" }}>
      <ToggleDemo accessibilityLabel="Toggle bold">
        <ToggleIcon as={TextBIcon} />
      </ToggleDemo>
    </View>
  )
}
import PhosphorSwift
import SwiftUI

struct ToggleExample: View {
  var body: some View {
    ToggleDemo(label: "Toggle bold") { Ph.textB.regular }
  }
}

struct ToggleDemo<Icon: View>: View {
  let variant: ToggleVariant
  let size: ToggleSize
  let label: LocalizedStringKey
  let icon: Icon

  @State private var isOn: Bool

  init(
    initial: Bool = false,
    variant: ToggleVariant = .default,
    size: ToggleSize = .default,
    label: LocalizedStringKey,
    @ViewBuilder icon: () -> Icon
  ) {
    self.variant = variant
    self.size = size
    self.label = label
    self.icon = icon()
    _isOn = State(initialValue: initial)
  }

  var body: some View {
    Toggle(isOn: $isOn) {
      icon.frame(width: 16, height: 16)
    }
    .toggleStyle(.variant(variant, size: size))
    .accessibilityLabel(Text(label))
  }
}
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.TextB
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Toggle
import com.esuiss.ui.components.ToggleSize
import com.esuiss.ui.components.ToggleVariant

@Composable
fun ToggleDemo(
    label: String,
    initial: Boolean = false,
    variant: ToggleVariant = ToggleVariant.Default,
    size: ToggleSize = ToggleSize.Default,
    enabled: Boolean = true,
    content: @Composable RowScope.() -> Unit,
) {
    var pressed by rememberSaveable { mutableStateOf(initial) }
    Toggle(
        pressed,
        { pressed = it },
        Modifier.semantics { contentDescription = label },
        variant = variant,
        size = size,
        enabled = enabled,
        content = content,
    )
}

@Composable
fun ToggleRow(content: @Composable () -> Unit) {
    Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
        content()
    }
}

@Composable
fun ToggleBold(initial: Boolean = false) {
    ToggleRow {
        ToggleDemo("Toggle bold", initial = initial) {
            Icon(PhosphorIcons.Regular.TextB, contentDescription = null)
        }
    }
}

Examples

Pressed

An icon toggle that starts in the on state.

Web

Web preview

import { TextBIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function TogglePressed() {
  const [pressed, setPressed] = React.useState(true)
  return (
    <View className="flex-row">
      <Toggle
        pressed={pressed}
        onPressedChange={setPressed}
        accessibilityLabel="Toggle bold"
      >
        <ToggleIcon as={TextBIcon} />
      </Toggle>
import { TextBIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function TogglePressed() {
  const [pressed, setPressed] = React.useState(true)
  return (
    <View style={{ flexDirection: "row" }}>
      <Toggle
        pressed={pressed}
        onPressedChange={setPressed}
        accessibilityLabel="Toggle bold"
      >
        <ToggleIcon as={TextBIcon} />
      </Toggle>
import PhosphorSwift
import SwiftUI

struct TogglePressedExample: View {
  var body: some View {
    ToggleDemo(initial: true, label: "Toggle bold") { Ph.textB.regular }
  }
}

struct ToggleDemo<Icon: View>: View {
  let variant: ToggleVariant
  let size: ToggleSize
  let label: LocalizedStringKey
  let icon: Icon

  @State private var isOn: Bool
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.TextB

Variants

The default and outline variants.

Web

Web preview

import { TextItalicIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleVariants() {
  return (
    <View className="flex-row gap-2">
      <Toggle accessibilityLabel="Toggle italic">
        <ToggleIcon as={TextItalicIcon} />
      </Toggle>
      <Toggle variant="outline" accessibilityLabel="Toggle italic">
        <ToggleIcon as={TextItalicIcon} />
      </Toggle>
    </View>
  )
}
import { TextItalicIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleVariants() {
  return (
    <View style={{ flexDirection: "row", gap: 8 }}>
      <Toggle accessibilityLabel="Toggle italic">
        <ToggleIcon as={TextItalicIcon} />
      </Toggle>
      <Toggle variant="outline" accessibilityLabel="Toggle italic">
        <ToggleIcon as={TextItalicIcon} />
      </Toggle>
    </View>
  )
}
import PhosphorSwift
import SwiftUI

struct ToggleVariantsExample: View {
  var body: some View {
    HStack(spacing: 8) {
      ToggleDemo(label: "Toggle italic") { Ph.textItalic.regular }
      ToggleDemo(variant: .outline, label: "Toggle italic") { Ph.textItalic.regular }
    }
  }
}

struct ToggleDemo<Icon: View>: View {
  let variant: ToggleVariant
  let size: ToggleSize
  let label: LocalizedStringKey
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.TextItalic

Sizes

Outline toggles in the sm, default and lg sizes.

Web

Web preview

import { TextBIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleSizes() {
  return (
    <View className="flex-row items-center gap-2">
      <Toggle size="sm" variant="outline" accessibilityLabel="Small">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
      <Toggle variant="outline" accessibilityLabel="Default">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
      <Toggle size="lg" variant="outline" accessibilityLabel="Large">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
import { TextBIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleSizes() {
  return (
    <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
      <Toggle size="sm" variant="outline" accessibilityLabel="Small">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
      <Toggle variant="outline" accessibilityLabel="Default">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
      <Toggle size="lg" variant="outline" accessibilityLabel="Large">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
import PhosphorSwift
import SwiftUI

struct ToggleSizesExample: View {
  var body: some View {
    HStack(spacing: 8) {
      ToggleDemo(variant: .outline, size: .sm, label: "Small") { Ph.textB.regular }
      ToggleDemo(variant: .outline, label: "Default") { Ph.textB.regular }
      ToggleDemo(variant: .outline, size: .lg, label: "Large") { Ph.textB.regular }
    }
  }
}

struct ToggleDemo<Icon: View>: View {
  let variant: ToggleVariant
  let size: ToggleSize
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular

With text

An outline toggle with an icon and a text label.

Web

Web preview

import { BookmarkSimpleIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Text } from "@/components/ui/text"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleWithText() {
  const [pressed, setPressed] = React.useState(false)
  return (
    <View className="flex-row">
      <Toggle
        pressed={pressed}
        onPressedChange={setPressed}
        variant="outline"
        accessibilityLabel="Bookmark"
      >
import { BookmarkSimpleIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Text } from "@/components/ui/text"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleWithText() {
  const [pressed, setPressed] = React.useState(false)
  return (
    <View style={{ flexDirection: "row" }}>
      <Toggle
        pressed={pressed}
        onPressedChange={setPressed}
        variant="outline"
        accessibilityLabel="Bookmark"
      >
import PhosphorSwift
import SwiftUI

struct WithTextDemo: View {
  @State private var isOn = false

  var body: some View {
    Toggle(isOn: $isOn) {
      Label {
        Text("Bookmark")
      } icon: {
        Ph.bookmarkSimple.regular
      }
    }
    .toggleStyle(.variant(.outline))
  }
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.BookmarkSimple

Disabled

Disabled toggles in the off and on states.

Web

Web preview

import { TextBIcon, TextItalicIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleDisabled() {
  return (
    <View className="flex-row gap-2">
      <Toggle disabled accessibilityLabel="Toggle bold">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
      <Toggle
        disabled
        defaultPressed
        variant="outline"
        accessibilityLabel="Toggle italic"
      >
import { TextBIcon, TextItalicIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Toggle, ToggleIcon } from "@/components/ui/toggle"

export default function ToggleDisabled() {
  return (
    <View style={{ flexDirection: "row", gap: 8 }}>
      <Toggle disabled accessibilityLabel="Toggle bold">
        <ToggleIcon as={TextBIcon} />
      </Toggle>
      <Toggle
        disabled
        defaultPressed
        variant="outline"
        accessibilityLabel="Toggle italic"
      >
import PhosphorSwift
import SwiftUI

struct ToggleDisabledExample: View {
  var body: some View {
    HStack(spacing: 8) {
      ToggleDemo(label: "Toggle bold") { Ph.textB.regular }
      ToggleDemo(initial: true, variant: .outline, label: "Toggle italic") { Ph.textItalic.regular }
    }
    .disabled(true)
  }
}

struct ToggleDemo<Icon: View>: View {
  let variant: ToggleVariant
  let size: ToggleSize
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.TextB

Accessibility

  • Uses the togglebutton role and reports checked and disabled in accessibilityState.
  • Inside a single-select Toggle Group, it uses the radio role instead.
  • Icon-only toggles need an accessibilityLabel.

API Reference

Toggle

The pressable two-state button.

PropTypeDefault
variant"default" | "outline""default"
size"default" | "sm" | "lg""default"

Also accepts the props of React.ComponentProps<typeof TogglePrimitive>.

Control the state with pressed and onPressedChange(pressed, details), or leave it uncontrolled with defaultPressed. Put text in a Text and icons in ToggleIcon. To group toggles with single or multiple selection, use Toggle Group. Changing the state triggers a selection haptic when a haptics adapter is provided through HapticsContext. toggleVariants, toggleStateClassName and toggleTextClassName are exported for reuse in custom components.

ToggleIcon

An icon sized for a toggle.

Also accepts the props of React.ComponentProps<typeof Icon>.

ToggleVariant

Values: .default, .outline.

ToggleSize

Values: .default, .sm, .lg.

.toggleStyle(.variant)

Style that creates VariantToggleStyle.

ParameterTypeDefault
_ variantToggleVariant: .default | .outline.default
sizeToggleSize: .default | .sm | .lg.default

ToggleVariant

Values: Default, Outline.

ToggleSize

Values: Default, Sm, Lg.

Toggle

The pressable two-state button.

ParameterTypeDefault
pressedBoolean-
onPressedChange(Boolean) -> Unit-
modifierModifierModifier
variantToggleVariant: Default | OutlineToggleVariant.Default
sizeToggleSize: Default | Sm | LgToggleSize.Default
enabledBooleantrue
interactionSourceMutableInteractionSource?null
content@Composable RowScope.() -> Unit-
textString-

Overloads: Toggle(pressed, onPressedChange, interactionSource, content), Toggle(text, pressed, onPressedChange).

NextToggle GroupPreviousToast

On this page

  1. 01Installation
  2. 02Usage
  3. 03Examples
    • Pressed
    • Variants
    • Sizes
    • With text
    • Disabled
  4. 04Accessibility
  5. 05API Reference
    • Toggle
  6. 06Installation
  7. 07Usage
  8. 08Examples
    • Pressed
    • Variants
    • Sizes
    • With text
    • Disabled
  9. 09Accessibility
  10. 10API Reference
    • Toggle
    • ToggleIcon
    • ToggleVariant
    • ToggleSize
    • .toggleStyle(.variant)
    • ToggleVariant
    • ToggleSize
    • Toggle