Toggle Switch
Animated toggle switch with custom effects
Disabled
Toggle Switch
A beautiful, animated toggle switch component for React, with smooth transitions and custom effects. Perfect for settings, preferences, and any binary state controls that need visual feedback and smooth interactions.
Features
- Smooth animations with Framer Motion
- Customizable colors, sizes, and effects
- Accessible and keyboard-friendly
- Responsive for all screen sizes
Installation
npm install motion/react
Basic Usage
import ToggleSwitch from "@/components/toggle-switch";function MyComponent() {return <ToggleSwitch />;}
Props
Prop | Type | Default | Description |
---|---|---|---|
checked | boolean | false | Whether the toggle is on (for controlled usage) |
onChange | function | - | Function called when toggle state changes (for controlled usage) |
label | string | - | Label for the toggle (for accessibility) |
variant | 'default' | 'modern' | 'minimal' | 'default' | Toggle style variant |
size | 'sm' | 'md' | 'lg' | 'md' | Toggle size |
disabled | boolean | false | Whether the toggle is disabled |
className | string | - | Additional CSS classes |
Examples
Basic Toggle
<ToggleSwitch />
Controlled Toggle
const [isOn, setIsOn] = useState(false);<ToggleSwitch checked={isOn} onChange={setIsOn} label="Enable notifications" />;
Different Variants
<ToggleSwitch variant="default" /><ToggleSwitch variant="modern" /><ToggleSwitch variant="minimal" />
Different Sizes
<ToggleSwitch size="sm" /><ToggleSwitch size="md" /><ToggleSwitch size="lg" />
Custom Colors
<ToggleSwitch className="bg-purple-500 data-[state=checked]:bg-green-500" />
With Icons
import { Sun, Moon } from "lucide-react";const [isOn, setIsOn] = useState(false);<div className="flex items-center gap-3"><ToggleSwitch checked={isOn} onChange={setIsOn} label="Toggle with icon" />{isOn ? (<Sun className="h-5 w-5 text-yellow-500" />) : (<Moon className="h-5 w-5 text-neutral-500" />)}</div>;
Best Practices
- Use clear, descriptive labels for accessibility
- Keep toggle states in sync with your app logic
- Test on mobile and desktop for responsiveness
- Use consistent styling throughout your app
Accessibility
- Proper ARIA labels for screen readers
- Keyboard navigation (Space/Enter to toggle)
- Clear focus indicators