Skip to main content
The Switch component provides an accessible toggle switch with a sliding thumb animation.

Basic Usage

import reflex_ui as ui

ui.switch()

Controlled State

class State(rx.State):
    enabled: bool = False

ui.switch(
    checked=State.enabled,
    on_checked_change=State.set_enabled
)

Event Handlers

ui.switch(
    on_checked_change=lambda value: rx.toast.success(f"Toggled: {value}")
)

Props Reference

checked
bool | Var[bool]
Current toggle state (controlled)
default_checked
bool
default:"False"
Initial toggle state (uncontrolled)
on_checked_change
EventHandler[bool]
Event fired when switch is toggled
disabled
bool
default:"False"
Disables switch interaction
required
bool
default:"False"
Makes switch required for form submission
read_only
bool
default:"False"
Prevents changing the switch state
name
str
Form field name for submission
value
str
default:"on"
Value submitted when switch is checked
unchecked_value
str
Value submitted when switch is unchecked
class_name
str
Additional CSS classes for styling

With Label

rx.el.label(
    ui.switch(checked=State.notifications),
    "Enable notifications",
    class_name="flex items-center gap-2"
)

Form Integration

rx.form(
    ui.switch(
        name="enabled",
        value="yes",
        default_checked=True
    ),
    on_submit=handle_submit
)

Real Example

From demo at demo/demo.py:44:
ui.switch(
    on_checked_change=lambda value: rx.toast.success(f"Value: {value}")
)

Compositional API

For custom layouts:
ui.switch.root(
    ui.switch.thumb(),
    checked=State.enabled,
    on_checked_change=State.set_enabled
)

Switch Components

switch.root

The main switch container with background.
ui.switch.root(
    ui.switch.thumb(),
    checked=True
)

switch.thumb

The sliding thumb element.
ui.switch.thumb()  # Auto-included in high-level API

Styling Classes

Access predefined styles via ui.switch.class_names:
  • ROOT: Switch track/background styles with checked states
  • THUMB: Sliding thumb styles with transform animations

Visual States

The switch automatically handles:
  • Unchecked: Gray background, thumb on left
  • Checked: Primary color background, thumb slides right
  • Disabled: Reduced opacity, cursor not-allowed
  • Focus: Outline visible for keyboard navigation

Animation

Smooth transitions powered by CSS:
  • 200ms ease-out for background color changes
  • 200ms ease-out for thumb translation
  • Shadow effects for depth

Accessibility

  • Keyboard accessible (Space/Enter to toggle)
  • Proper ARIA attributes
  • Focus indicators
  • Screen reader support

Implementation Details

From source code at reflex_ui/components/base/switch.py:94:
  • Built on Base UI Switch primitives
  • High-level wrapper auto-creates root with thumb
  • Uses data attributes for styling states
  • Renders hidden checkbox input for form submission
  • Thumb translates 3 units (0.75rem) when checked

Build docs developers (and LLMs) love