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, useColorScheme } from "react-native";
import { cn } from "@/lib/utils";

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 dark = useColorScheme() === "dark";
  const off = trackColorOff ?? (dark ? "#27272a" : "#e4e4e7");
  const on = trackColorOn ?? (dark ? "#fafafa" : "#18181b");
  // 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 ?? (value ? (dark ? "#18181b" : "#ffffff") : "#ffffff");

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