AniUI

Switch

Toggle switch for boolean settings.

Web preview — components render natively on iOS & Android
import { Switch } from "@/components/ui/switch";
import { useState } from "react";

export function MyScreen() {
  const [enabled, setEnabled] = useState(false);
  return (
    <Switch value={enabled} onValueChange={setEnabled} />
  );
}

Installation#

npx @aniui/cli add switch

Usage#

app/index.tsx
import { Switch } from "@/components/ui/switch";
import { useState } from "react";

export function MyScreen() {
  const [enabled, setEnabled] = useState(false);
  return (
    <Switch value={enabled} onValueChange={setEnabled} />
  );
}

Props#

PropTypeDefault
value
boolean
false
onValueChange
(value: boolean) => void
trackColorOff
string

Override the off-state track color. Defaults adapt to light/dark mode.

trackColorOn
string

Override the on-state track color. Defaults adapt to light/dark mode.

thumbColor
string

Override the thumb color. Defaults to a value that contrasts with the active track on both iOS and Android.

className
string

Also accepts all Switch props from React Native.

Accessibility#

  • accessibilityRole="switch" wrapping the native React Native Switch.
  • On/off state is announced automatically by the platform.

Source#

components/ui/switch.tsx
import React from "react";
import { View, Switch as RNSwitch } from "react-native";
import { cn } from "@/lib/utils";
import { useThemeColors } from "@/components/ui/theme-provider";

export interface SwitchProps extends React.ComponentPropsWithoutRef<typeof RNSwitch> {
  className?: string;
  trackColorOff?: string;
  trackColorOn?: string;
  thumbColor?: string;
}

export function Switch({ className, trackColorOff, trackColorOn, thumbColor, value, ...props }: SwitchProps) {
  const colors = useThemeColors();
  const off = trackColorOff ?? colors.border;
  const on = trackColorOn ?? colors.foreground;
  // Thumb must contrast with the track in every state. In dark mode the ON
  // track is near-white, so a default white thumb would disappear on iOS.
  const thumb = thumbColor ?? colors.background;

  return (
    <View className={cn("", className)}>
      <RNSwitch
        value={value}
        trackColor={{ false: off, true: on }}
        thumbColor={thumb}
        ios_backgroundColor={off}
        accessibilityRole="switch"
        {...props}
      />
    </View>
  );
}