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

Switch

A toggle control that turns a single setting on or off.

Switch 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 { Switch } from "@/components/ui/switch"

export default function SwitchDemo() {
  return <Switch aria-label="Wi-Fi" />
}

Switch wraps the switch primitive of the chosen base and renders the track and thumb together. The thumb stretches while pressed, and the track fills with the primary color when on.

Use a switch for settings that take effect immediately. To select an option in a form that's submitted later, use Checkbox.

Installation

$ pnpm dlx shadcn@latest add @esuiss/switch

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 switch
  1. Install the following dependencies and add the cn helper:
$ pnpm add @base-ui/react
  1. Copy and paste the following code into your project.
components/ui/switch.tsx
"use client"

import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { cn } from "@/lib/utils"

function Switch({
  className,
  size = "default",
  ...props
}: SwitchPrimitive.Root.Props & {
  size?: "sm" | "default"
}) {
  return (
    <SwitchPrimitive.Root
      data-slot="switch"
      data-size={size}
  1. Update the import paths to match your project setup.

Usage

import { Switch } from "@/components/ui/switch"
<Switch aria-label="Wi-Fi" />

Examples

Checked

Set defaultChecked to start the switch in the on state.

Set defaultSelected to start the switch in the on state.

import { Switch } from "@/components/ui/switch"

export default function SwitchChecked() {
  return <Switch defaultChecked aria-label="Wi-Fi" />
}

Sizes

Use the size prop to choose between sm and default.

import { Switch } from "@/components/ui/switch"

export default function SwitchSizes() {
  return (
    <div className="flex items-center gap-4">
      <Switch size="sm" defaultChecked aria-label="Wi-Fi" />
      <Switch size="default" defaultChecked aria-label="Bluetooth" />
    </div>
  )
}

With label

Wrap the switch and its text in a Label so the text names and toggles it too.

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export default function SwitchWithLabel() {
  return (
    <Label>
      <Switch />
      Airplane mode
    </Label>
  )
}

Disabled

Set disabled to turn the switch off; the example shows the off and on states.

Set isDisabled to turn the switch off; the example shows the off and on states.

import { Switch } from "@/components/ui/switch"

export default function SwitchDisabled() {
  return (
    <div className="flex items-center gap-4">
      <Switch disabled aria-label="Wi-Fi" />
      <Switch disabled defaultChecked aria-label="Bluetooth" />
    </div>
  )
}

Invalid

Mark the switch with aria-invalid to show an error state with a destructive border.

Mark the switch with isInvalid to show an error state with a destructive border.

import { Switch } from "@/components/ui/switch"

export default function SwitchInvalid() {
  return <Switch aria-invalid aria-label="Accept terms" />
}

Accessibility

  • Renders with the switch role and aria-checked.
  • Give it a name with aria-label or by wrapping it in a Label.
  • Space toggles the focused switch.
  • A disabled switch ignores clicks and keyboard presses.

API Reference

Switch

The switch track and its sliding thumb.

PropTypeDefault
size"sm" | "default""default"
checkedboolean—
defaultCheckedbooleanfalse
onCheckedChange(checked: boolean) => void—
disabledbooleanfalse
PropTypeDefault
size"sm" | "default""default"
isSelectedboolean—
defaultSelectedbooleanfalse
onChange(isSelected: boolean) => void—
isDisabledbooleanfalse
isInvalidbooleanfalse

Also accepts the props of the primitive part it wraps.

Use defaultChecked for an uncontrolled switch, or checked with onCheckedChange to control it. onCheckedChange is called when the switch is toggled.

Use defaultSelected for an uncontrolled switch, or isSelected with onChange to control it. onChange is called when the switch is toggled.

A transparent hit area extends around the track to make it easier to tap, and the thumb's travel flips in right-to-left layouts. The parts set data-slot="switch" and data-slot="switch-thumb", plus data-size and the primitive's state attributes, for styling.

Web

Web preview

import * as React from "react"
import { Switch } from "@/components/ui/switch"

export default function SwitchDemoExample() {
  const [checked, setChecked] = React.useState(false)
  return <Switch checked={checked} onCheckedChange={setChecked} />
}
import SwiftUI

struct SwitchExample: View {
  var body: some View {
    SwitchDemo(initial: false)
  }
}

struct SwitchDemo: View {
  var size: SwitchStyle.Size = .default
  var label: LocalizedStringKey?

  @State private var checked: Bool

  init(initial: Bool, size: SwitchStyle.Size = .default, label: LocalizedStringKey? = nil) {
    self.size = size
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 com.esuiss.ui.components.Switch

@Composable
fun SwitchExample() {
    SwitchDemo(initial = false)
}

@Composable
fun SwitchDemo(initial: Boolean) {
    var checked by rememberSaveable { mutableStateOf(initial) }
    Switch(checked, { checked = it })

Switch is a pressable track with a round thumb that slides between the off and on positions. The thumb animates with Reanimated and stretches slightly while pressed. It comes in two sizes, default and sm, and has an invalid state that adds a destructive border.

Use a switch for settings that take effect immediately. For choices that are submitted later, use Checkbox. The switch has a hit slop around it, so it is easier to press than its visual size.

Installation

$ pnpm dlx shadcn@latest add @esuiss/switch

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

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

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

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

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

$ pnpm dlx @esuiss/ui@latest add switch --platform kotlin
  1. Install the following dependencies:
npx expo install cn react-native-reanimated react-native-worklets
  1. 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/switch.tsx
import * as React from "react"
import { type GestureResponderEvent, Pressable, View } from "react-native"
import { createChangeEventDetails, REASONS } from "./event-details"
import { useHaptics } from "./haptics"
import type { BaseUIChangeEventDetails, BaseUIComponentProps } from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ChangeEventReason = typeof REASONS.triggerPress | typeof REASONS.none

type ChangeEventDetails = BaseUIChangeEventDetails<ChangeEventReason>

interface RootState {
  checked: boolean
  disabled: boolean
  readOnly: boolean
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/switch.tsx:
uniwind/components/ui/switch.tsx
import { cn } from "cn"
import * as React from "react"
import type { GestureResponderEvent } from "react-native"
import Animated, {
  Easing,
  ReduceMotion,
  useAnimatedStyle,
  withTiming,
} from "react-native-reanimated"
import * as SwitchPrimitives from "@/components/primitives/switch"
import { resolveClassName } from "@/components/primitives/use-render"

type SwitchSize = "default" | "sm"

const HIT_SLOP = { top: 8, bottom: 8, left: 12, right: 12 }
  1. Update the import paths to match your project setup.
  1. Install the following dependencies:
npx expo install cn react-native-reanimated react-native-worklets
  1. 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/switch.tsx
import * as React from "react"
import { type GestureResponderEvent, Pressable, View } from "react-native"
import { createChangeEventDetails, REASONS } from "./event-details"
import { useHaptics } from "./haptics"
import type { BaseUIChangeEventDetails, BaseUIComponentProps } from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ChangeEventReason = typeof REASONS.triggerPress | typeof REASONS.none

type ChangeEventDetails = BaseUIChangeEventDetails<ChangeEventReason>

interface RootState {
  checked: boolean
  disabled: boolean
  readOnly: boolean
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/switch.tsx:
nativewind/components/ui/switch.tsx
import { cn } from "cn"
import * as React from "react"
import type { GestureResponderEvent } from "react-native"
import Animated, {
  Easing,
  ReduceMotion,
  useAnimatedStyle,
  withTiming,
} from "react-native-reanimated"
import * as SwitchPrimitives from "@/components/primitives/switch"
import { resolveClassName } from "@/components/primitives/use-render"

type SwitchSize = "default" | "sm"

const HIT_SLOP = { top: 8, bottom: 8, left: 12, right: 12 }
  1. Update the import paths to match your project setup.
  1. Install the following dependencies:
npx expo install react-native-reanimated react-native-worklets
  1. 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/switch.tsx
import * as React from "react"
import { type GestureResponderEvent, Pressable, View } from "react-native"
import { createChangeEventDetails, REASONS } from "./event-details"
import { useHaptics } from "./haptics"
import type { BaseUIChangeEventDetails, BaseUIComponentProps } from "./types"
import { useControllableState } from "./use-controllable-state"
import { useRender } from "./use-render"

type ChangeEventReason = typeof REASONS.triggerPress | typeof REASONS.none

type ChangeEventDetails = BaseUIChangeEventDetails<ChangeEventReason>

interface RootState {
  checked: boolean
  disabled: boolean
  readOnly: boolean
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/switch.tsx:
stylesheet/components/ui/switch.tsx
import * as React from "react"
import { type GestureResponderEvent, StyleSheet } from "react-native"
import Animated, {
  Easing,
  ReduceMotion,
  useAnimatedStyle,
  withTiming,
} from "react-native-reanimated"
import * as SwitchPrimitives from "@/components/primitives/switch"
import { shadow, type ThemeColors, useTheme } from "@/components/ui/theme"

type SwitchSize = "default" | "sm"

const HIT_SLOP = { top: 8, bottom: 8, left: 12, right: 12 }

const THUMB = {
  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/Switch.swift
import SwiftUI

public struct SwitchStyle: ToggleStyle {
  public enum Size: CaseIterable, Sendable {
    case `default`, sm

    var track: CGSize {
      switch self {
      case .default: CGSize(width: 52, height: 24)
      case .sm: CGSize(width: 44, height: 20)
      }
    }

    var thumbHeight: CGFloat {
      switch self {
      case .default: 20
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")
}
  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/Switch.kt
package com.esuiss.ui.components

import androidx.compose.animation.core.animateDpAsState
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.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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/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 * as React from "react"
import { Switch } from "@/components/ui/switch"

function SwitchDemo({ initial = false }: { initial?: boolean }) {
  const [checked, setChecked] = React.useState(initial)
  return <Switch checked={checked} onCheckedChange={setChecked} />
}

export function SwitchExample() {
  return (
    <SwitchDemo />
  )
}
import SwiftUI

struct SwitchExample: View {
  var body: some View {
    SwitchDemo(initial: false)
  }
}

struct SwitchDemo: View {
  var size: SwitchStyle.Size = .default
  var label: LocalizedStringKey?

  @State private var checked: Bool

  init(initial: Bool, size: SwitchStyle.Size = .default, label: LocalizedStringKey? = nil) {
    self.size = size
    self.label = label
    _checked = State(initialValue: initial)
  }

  var body: some View {
    if let label {
      Toggle(isOn: $checked) { EmptyView() }
        .toggleStyle(.switch(size: size))
        .accessibilityLabel(Text(label))
    } else {
      Toggle(isOn: $checked) { EmptyView() }
        .toggleStyle(.switch(size: size))
    }
  }
}
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 com.esuiss.ui.components.Switch

@Composable
fun SwitchExample() {
    SwitchDemo(initial = false)
}

@Composable
fun SwitchDemo(initial: Boolean) {
    var checked by rememberSaveable { mutableStateOf(initial) }
    Switch(checked, { checked = it })
}

Examples

Checked

A switch that starts on.

Web

Web preview

import * as React from "react"
import { Switch } from "@/components/ui/switch"

export default function SwitchChecked() {
  const [checked, setChecked] = React.useState(true)
  return <Switch checked={checked} onCheckedChange={setChecked} />
}
import SwiftUI

struct SwitchCheckedExample: View {
  var body: some View {
    SwitchDemo(initial: true)
  }
}

struct SwitchDemo: View {
  var size: SwitchStyle.Size = .default
  var label: LocalizedStringKey?

  @State private var checked: Bool

  init(initial: Bool, size: SwitchStyle.Size = .default, label: LocalizedStringKey? = nil) {
    self.size = size
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 com.esuiss.ui.components.Switch

@Composable
fun SwitchCheckedExample() {
    SwitchDemo(initial = true)
}

@Composable
fun SwitchDemo(initial: Boolean) {
    var checked by rememberSaveable { mutableStateOf(initial) }
    Switch(checked, { checked = it })

Sizes

Set size to sm or default; the example shows both side by side.

Web

Web preview

import { View } from "react-native"
import { Switch } from "@/components/ui/switch"

export default function SwitchSizes() {
  return (
    <View className="flex-row items-center gap-4">
      <Switch size="sm" defaultChecked accessibilityLabel="Wi-Fi" />
      <Switch defaultChecked accessibilityLabel="Bluetooth" />
    </View>
  )
}
import { View } from "react-native"
import { Switch } from "@/components/ui/switch"

export default function SwitchSizes() {
  return (
    <View style={{ flexDirection: "row", alignItems: "center", gap: 16 }}>
      <Switch size="sm" defaultChecked accessibilityLabel="Wi-Fi" />
      <Switch defaultChecked accessibilityLabel="Bluetooth" />
    </View>
  )
}
import SwiftUI

struct SwitchSizesExample: View {
  var body: some View {
    HStack(spacing: 16) {
      SwitchDemo(initial: true, size: .sm, label: "Wi-Fi")
      SwitchDemo(initial: true, label: "Bluetooth")
    }
  }
}

struct SwitchDemo: View {
  var size: SwitchStyle.Size = .default
  var label: LocalizedStringKey?

  @State private var checked: Bool
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
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.esuiss.ui.components.Switch
import com.esuiss.ui.components.SwitchSize

fun Modifier.label(text: String): Modifier = semantics { contentDescription = text }

With label

A controlled switch next to a pressable label.

Web

Web preview

import * as React from "react"
import { View } from "react-native"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export default function SwitchWithLabel() {
  const [checked, setChecked] = React.useState(false)
  return (
    <View className="flex-row items-center gap-2">
      <Switch
        accessibilityLabelledBy="airplane-mode"
        checked={checked}
        onCheckedChange={setChecked}
      />
      <Label nativeID="airplane-mode" onPress={() => setChecked((v) => !v)}>
        Airplane mode
import * as React from "react"
import { View } from "react-native"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export default function SwitchWithLabel() {
  const [checked, setChecked] = React.useState(false)
  return (
    <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
      <Switch
        accessibilityLabelledBy="airplane-mode"
        checked={checked}
        onCheckedChange={setChecked}
      />
      <Label nativeID="airplane-mode" onPress={() => setChecked((v) => !v)}>
        Airplane mode
import SwiftUI

struct WithLabelDemo: View {
  @State private var checked = false

  var body: some View {
    Toggle(isOn: $checked) {
      FieldLabel("Airplane mode")
    }
    .toggleStyle(.switch(size: .default))
  }
}
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.esuiss.ui.components.Label

With description

A switch with a label and a line of supporting text.

React Native
Switch with description in React Native, light modeSwitch with description in React Native, dark mode
import * as React from "react"
import { View } from "react-native"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Text } from "@/components/ui/text"

export default function SwitchWithDescription() {
  const [checked, setChecked] = React.useState(true)
  return (
    <View className="flex-row items-center justify-between gap-4 rounded-2xl bg-muted p-4">
      <View className="flex-1 gap-1">
        <Label nativeID="marketing" onPress={() => setChecked((v) => !v)}>
          Marketing emails
        </Label>
        <Text className="text-sm text-muted-foreground">
          Receive emails about new products.
import * as React from "react"
import { View } from "react-native"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Text } from "@/components/ui/text"
import { fontSize, radius, useTheme } from "@/components/ui/theme"

export default function SwitchWithDescription() {
  const { colors } = useTheme()
  const [checked, setChecked] = React.useState(true)
  return (
    <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between", gap: 16, borderRadius: radius["2xl"], backgroundColor: colors.muted, padding: 16 }}>
      <View style={{ flex: 1, gap: 4 }}>
        <Label nativeID="marketing" onPress={() => setChecked((v) => !v)}>
          Marketing emails
        </Label>
import SwiftUI

struct WithDescriptionDemo: View {
  @State private var checked = true

  var body: some View {
    HStack(spacing: 16) {
      VStack(alignment: .leading, spacing: 4) {
        FieldLabel("Marketing emails")
          .onTapGesture { checked.toggle() }
        Text("Receive emails about new products.")
          .textStyle(.sm)
          .foregroundStyle(EsuissColor.mutedForeground)
      }
      .frame(maxWidth: .infinity, alignment: .leading)
      Toggle(isOn: $checked) { EmptyView() }
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment

Disabled

Disabled switches in the off and on states.

Web

Web preview

import { View } from "react-native"
import { Switch } from "@/components/ui/switch"

export default function SwitchDisabled() {
  return (
    <View className="gap-4">
      <Switch disabled checked={false} onCheckedChange={() => undefined} />
      <Switch disabled checked onCheckedChange={() => undefined} />
    </View>
  )
}
import { View } from "react-native"
import { Switch } from "@/components/ui/switch"

export default function SwitchDisabled() {
  return (
    <View style={{ gap: 16 }}>
      <Switch disabled checked={false} onCheckedChange={() => undefined} />
      <Switch disabled checked onCheckedChange={() => undefined} />
    </View>
  )
}
import SwiftUI

struct SwitchDisabledExample: View {
  var body: some View {
    VStack(alignment: .leading, spacing: 16) {
      Toggle(isOn: .constant(false)) { EmptyView() }
      Toggle(isOn: .constant(true)) { EmptyView() }
    }
    .toggleStyle(.switch(size: .default))
    .disabled(true)
  }
}
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Switch

@Composable
fun SwitchDisabled() {
    Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Switch(false, {}, enabled = false)
        Switch(true, {}, enabled = false)
    }
}

Invalid

Set invalid to add a destructive border; the example shows the switch next to its label.

Web

Web preview

import { View } from "react-native"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export default function SwitchInvalid() {
  return (
    <View className="flex-row items-center gap-2">
      <Switch invalid accessibilityLabelledBy="terms-switch" />
      <Label nativeID="terms-switch">Accept terms</Label>
    </View>
  )
}
import { View } from "react-native"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export default function SwitchInvalid() {
  return (
    <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
      <Switch invalid accessibilityLabelledBy="terms-switch" />
      <Label nativeID="terms-switch">Accept terms</Label>
    </View>
  )
}
import SwiftUI

struct InvalidDemo: View {
  @State private var checked = false

  var body: some View {
    Toggle(isOn: $checked) {
      FieldLabel("Accept terms")
    }
    .toggleStyle(.switch(size: .default))
    .invalid()
  }
}
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
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.esuiss.ui.components.Label
import com.esuiss.ui.components.Switch

fun Modifier.label(text: String): Modifier = semantics { contentDescription = text }

Accessibility

  • The root has the switch role and reports checked and disabled in its accessibility state, so VoiceOver and TalkBack announce whether it is on.
  • The thumb is hidden from the accessibility tree.
  • Label every switch with accessibilityLabel or accessibilityLabelledBy.
  • The thumb animation follows the system reduce motion setting.

API Reference

Switch

The switch track and its sliding thumb.

PropTypeDefault
sizeSwitchSize"default"
invalidboolean-

Also accepts the props of React.ComponentProps<typeof SwitchPrimitives.Root>.

Use defaultChecked for an uncontrolled switch, or checked with onCheckedChange to control it. invalid adds a destructive border when the switch is not disabled. A disabled switch is shown at opacity-50.

A switch has no visible text of its own. Pair it with a Label and link them with accessibilityLabelledBy and the label's nativeID, or set an accessibilityLabel. Give the Label an onPress that toggles the value if the label should be pressable too.

.toggleStyle(.switch)

Style that creates SwitchStyle.

ParameterTypeDefault
sizeSwitchStyle.Size: .default | .sm-

SwitchSize

Values: Default, Sm.

Switch

The switch track and its sliding thumb.

ParameterTypeDefault
checkedBoolean-
onCheckedChange((Boolean) -> Unit)?-
modifierModifierModifier
sizeSwitchSize: Default | SmSwitchSize.Default
enabledBooleanLocalFieldState.current.enabled
invalidBooleanLocalFieldState.current.invalid
interactionSourceMutableInteractionSource?null
NextTab BarPreviousSpinner

On this page

  1. 01Installation
  2. 02Usage
  3. 03Examples
    • Checked
    • Sizes
    • With label
    • Disabled
    • Invalid
  4. 04Accessibility
  5. 05API Reference
    • Switch
  6. 06Installation
  7. 07Usage
  8. 08Examples
    • Checked
    • Sizes
    • With label
    • With description
    • Disabled
    • Invalid
  9. 09Accessibility
  10. 10API Reference
    • Switch
    • .toggleStyle(.switch)
    • SwitchSize
    • Switch