Biji UI

Switch

A control that allows the user to toggle between on and off states.

Installation

biji-ui = { version = "0.5.0", features = ["switch"] }

Usage

use leptos::prelude::*;
use biji_ui::components::switch;

#[component]
pub fn MySwitch() -> impl IntoView {
    view! {
        <switch::Root class="relative inline-flex w-11 h-6 rounded-full border-2 border-transparent transition-colors bg-zinc-300 dark:bg-zinc-600 data-[state=checked]:bg-primary">
            <switch::Thumb class="block w-5 h-5 rounded-full bg-white data-[state=checked]:bg-primary-foreground shadow-md transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0" />
        </switch::Root>
    }
}

RootWith

Use <RootWith> when you need direct access to SwitchState inside the children. The let:s binding exposes s.checked and s.data_state as reactive signals for custom rendering.

use leptos::prelude::*;
use biji_ui::components::switch;

#[component]
pub fn LabeledSwitch() -> impl IntoView {
    let switch_class = "relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background bg-zinc-300 dark:bg-zinc-600 data-[state=checked]:bg-primary";
    let thumb_class = "pointer-events-none block h-5 w-5 rounded-full bg-white data-[state=checked]:bg-primary-foreground shadow-md ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0";

    view! {
        <label class="flex items-center gap-3 cursor-pointer select-none">
            <switch::RootWith default_checked=false class={switch_class} let:s>
                <switch::Thumb class={thumb_class} />
                <span class="sr-only">{move || if s.checked.get() { "On" } else { "Off" }}</span>
            </switch::RootWith>
            <span class="text-sm font-medium">"Notifications"</span>
        </label>
    }
}

API Reference

Root / RootWith

NameTypeDefaultDescription
classString""CSS class applied to the switch button.
checkedboolfalseThe initial checked (on) state of the switch.
disabledboolfalseWhen true, prevents the switch from being toggled.

Thumb

NameTypeDefaultDescription
classString""CSS class applied to the thumb span.

Data Attributes

AttributeDescription
data-state"checked" when on; "unchecked" when off. Present on Root and Thumb.
data-disabledPresent on Root and Thumb when the switch is disabled.

Keyboard Navigation

KeyDescription
SpaceToggles the switch between on and off when focused.