Switch

Rust UI component that displays a control that allows the user to toggle between checked and not checked.

utils
  • Rust UI Icons - CopyCopy Demo
Airplane
use leptos::prelude::*;

use crate::components::ui::switch::{Switch, SwitchLabel};

#[component]
pub fn DemoSwitch() -> impl IntoView {
    view! {
        <div class="flex gap-2">
            <Switch />
            <SwitchLabel>"Airplane"</SwitchLabel>
        </div>
    }
}

Installation

You can run either of the following commands:

# cargo install ui-cli --force
ui add demo_switch
ui add switch

Update the imports to match your project setup.

Copy and paste the following code into your project:

components/ui/switch.rs

use leptos::prelude::*;
use leptos_ui::clx;

mod components {
    use super::*;
    clx! {SwitchLabel, span, "text-sm font-medium"}
}

pub use components::*;

#[component]
pub fn Switch() -> impl IntoView {
    // let input_ref = NodeRef::<html::Input>::new();

    // let handle_keydown = move |e: web_sys::KeyboardEvent| {
    //     if e.key() == " " || e.key() == "Enter" {
    //         e.prevent_default();
    //         if let Some(input) = input_ref.get() {
    //             input.click();
    //         }
    //     }
    // };

    view! {
        <label
            class="inline-flex relative items-center cursor-pointer"
            // on:keydown=handle_keydown
            tabindex="0"
        >
            <input type="checkbox" value="" class="sr-only peer" />
            <div class="w-11 h-6 bg-gray-200 rounded-full dark:bg-gray-700 dark:border-gray-600 peer-focus:outline-hidden peer-focus:ring-ring/50 peer-focus:ring-[3px] peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary" />
        </label>
    }
}

Update the imports to match your project setup.

Usage

use crate::components::ui::switch::Switch;
<Switch checked=false />