Toggle
A customizable toggle switch component for binary states with animation.
Toggle
The Toggle component is a switch that allows users to toggle between two states (on/off, true/false). It features a smooth animation and support for both controlled and uncontrolled usage patterns.
Features
- Animated Transition: Smooth spring animation when toggling states
- Controlled & Uncontrolled Modes: Can be used with or without external state management
- Disabled State: Support for disabled/inactive state
- Customizable Styling: Control for appearance via className
- Dark Mode Support: Automatic light/dark mode styles
Import
Props
Prop | Type | Default | Description |
---|---|---|---|
value | boolean | — | Current state of the toggle (controlled mode) |
onChange | (value: boolean) => void | — | Function called when the toggle state changes |
disabled | boolean | false | Whether the toggle is disabled |
className | string | '' | Additional Tailwind classes for the toggle |
Usage Examples
Basic Toggle (Uncontrolled)
Controlled Toggle
Disabled Toggle
Custom Styled Toggle
Toggle with Label
Form Integration Example
Settings List Example
Best Practices
Meaningful Labels
Always provide clear labels for toggles to indicate what they control:
Controlled vs. Uncontrolled Usage
Choose the appropriate usage pattern based on your needs:
Immediate Feedback
Provide immediate visual feedback when a toggle changes state:
Implementation Details
The Toggle component uses React Native's Pressable
, View
, and Animated
components to create a smooth toggling experience. It features a spring animation that provides a natural, bouncy feel when toggling between states.
The component works in both controlled and uncontrolled modes:
- In controlled mode, the
value
prop determines the toggle state - In uncontrolled mode, the component manages its own state internally
The toggle uses Tailwind classes for styling, with different background colors for the on and off states. The component supports both light and dark modes through conditional styling.
Notes
- The spring animation uses a bounciness of 4 and speed of 12 for a natural feel
- In controlled mode (
value
prop provided), the internal state is ignored - When disabled, the toggle has reduced opacity and doesn't respond to presses
- The toggle uses a color from the theme's highlight palette when in the "on" state