Function leptos_use::use_color_mode
source · pub fn use_color_mode() -> UseColorModeReturn
Expand description
Reactive color mode (dark / light / customs) with auto data persistence.
§Demo
§Usage
let UseColorModeReturn {
mode, // Signal<ColorMode::dark | ColorMode::light>
set_mode,
..
} = use_color_mode();
By default, it will match with users’ browser preference using [use_preferred_dark
] (a.k.a. ColorMode::Auto
).
When reading the signal, it will by default return the current color mode (ColorMode::Dark
, ColorMode::Light
or
your custom modes ColorMode::Custom("some-custom")
). The ColorMode::Auto
variant can
be included in the returned modes by enabling the emit_auto
option and using use_color_mode_with_options
.
When writing to the signal (set_mode
), it will trigger DOM updates and persist the color mode to local
storage (or your custom storage). You can pass ColorMode::Auto
to set back to auto mode.
mode.get(); // ColorMode::Dark or ColorMode::Light
set_mode.set(ColorMode::Dark); // change to dark mode and persist
set_mode.set(ColorMode::Auto); // change to auto mode
§Options
let UseColorModeReturn { mode, set_mode, .. } = use_color_mode_with_options(
UseColorModeOptions::default()
.attribute("theme") // instead of writing to `class`
.custom_modes(vec![
// custom colors in addition to light/dark
"dim".to_string(),
"cafe".to_string(),
]),
); // Signal<ColorMode::Dark | ColorMode::Light | ColorMode::Custom("dim") | ColorMode::Custom("cafe")>
§Cookies
To persist color mode in a cookie, use use_cookie_with_options
and specify .cookie_enabled(true)
.
Note: To work with SSR you have to add the
axum
oractix
feature as described in [use_cookie
].
let UseColorModeReturn { mode, set_mode, .. } = use_color_mode_with_options(
UseColorModeOptions::default()
.cookie_enabled(true),
);
// This adds the color mode class to the `<html>` element even with SSR
view! {
<Html class=move || mode.get().to_string()/>
}
For a working example please check out the ssr example.
§Server-Side Rendering
On the server this will by default return ColorMode::Light
. Persistence with storage is disabled.
If cookie_enabled
is set to true
, cookies will be used and if present this value will be used
on the server as well as on the client. Please note that you have to add the axum
or actix
feature as described in [use_cookie
].
§See also
- [
use_preferred_dark
] - [
use_storage
] - [
use_cookie
]