Switch

A toggle between two states

yarnnpmbunpnpm
import type { SizeTokens } from 'tamagui'
import { Label, Separator, Switch, XStack, YStack, styled } from 'tamagui'
export function SwitchDemo() {
return (
<YStack width={200} alignItems="center" gap="$3">
<XStack gap="$3" $xs={{ flexDirection: 'column' }}>
<SwitchWithLabel size="$2" />
<SwitchWithLabel size="$2" defaultChecked />
</XStack>
<XStack gap="$3" $xs={{ flexDirection: 'column' }}>
<SwitchWithLabel size="$3" />
<SwitchWithLabel size="$3" defaultChecked />
</XStack>
<XStack gap="$3" $xs={{ flexDirection: 'column' }}>
<SwitchWithLabel size="$4" />
<SwitchWithLabel size="$4" defaultChecked />
</XStack>
</YStack>
)
}
export function SwitchWithLabel(props: { size: SizeTokens; defaultChecked?: boolean }) {
const id = `switch-${props.size.toString().slice(1)}-${props.defaultChecked ?? ''}}`
return (
<XStack width={200} alignItems="center" gap="$4">
<Label paddingRight="$0" minWidth={90} justifyContent="flex-end" size={props.size} htmlFor={id} >
Accept
</Label>
<Separator minHeight={20} vertical />
<Switch id={id} size={props.size} defaultChecked={props.defaultChecked}>
<Switch.Thumb animation="quicker" />
</Switch>
</XStack>
)
}

Features

  • Accessible, easy to compose and customize.

  • Style and animate both frame and thumb.

  • Sizable & works controlled or uncontrolled.

  • Native prop that renders native Switch on mobile

Installation

Switch is already installed in tamagui, or you can install it independently:

yarn add @tamagui/switch

Usage

import { Switch } from 'tamagui' // or '@tamagui/switch'
export default () => (
<Switch size="$4">
<Switch.Thumb animation="bouncy" />
</Switch>
)

API Reference

Switch

Switch extends Stack views inheriting all the Tamagui standard props, plus:

Props

  • labeledBy

    string

    Set aria-labeled-by.

  • name

    string

    Equivalent to input name.

  • value

    string

    Give it a value (for use in HTML forms).

  • checked

    boolean

    Control the input.

  • defaultChecked

    boolean

    Uncontrolled default value.

  • required

    boolean

    Sets aria-required.

  • onCheckedChange

    (checked: boolean) => void

  • unstyled

    boolean

    Default: 

    false

    When true, remove all default tamagui styling.

  • native

    NativeValue<"mobile" | "ios" | "android">

    Render to a native switch. (Not supported on web)

  • nativeProps

    SwitchProps (from `react-native`)

    Props to pass to the native Switch;

  • Switch.Thumb

    Switch.Thumb extends Stack views inheriting all the Tamagui standard props, plus:

    Props

  • unstyled

    boolean

    Default: 

    false

    When true, remove all default tamagui styling.