Switch
Themed controlled/uncontrolled RN Switch wrapper. Same checked API as web Switch.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add switchSource files
Expand a file to read the source the installer copies into your app.
components/ui/switch/Switch.tsx
import * as React from 'react'
import { Switch as RNSwitch, type SwitchProps as RNSwitchProps } from 'react-native'
import { useThemeColors } from '@/lib/theme'
export interface SwitchProps extends RNSwitchProps {
checked?: boolean
defaultChecked?: boolean
onCheckedChange?: (checked: boolean) => void
}
function Switch({
checked,
defaultChecked,
onCheckedChange,
onValueChange,
value,
accessibilityState,
...props
}: SwitchProps) {
const colors = useThemeColors()
const isControlled = checked !== undefined || value !== undefined
const [internal, setInternal] = React.useState(defaultChecked ?? value ?? false)
const resolved = (checked ?? value ?? internal) as boolean
function handleChange(next: boolean) {
if (!isControlled) setInternal(next)
onCheckedChange?.(next)
onValueChange?.(next)
}
return (
<RNSwitch
accessibilityRole="switch"
accessibilityState={{
...accessibilityState,
checked: resolved,
disabled: props.disabled ?? accessibilityState?.disabled,
}}
trackColor={{ false: colors.input, true: colors.primary }}
thumbColor={resolved ? colors.switchThumbChecked : colors.switchThumb}
ios_backgroundColor={colors.input}
value={resolved}
onValueChange={handleChange}
{...props}
/>
)
}
export { Switch }
components/ui/switch/index.ts
export { Switch, type SwitchProps } from './Switch'