use_css_var
Manipulate CSS variables.
Demo
Usage
use leptos::prelude::*;
use leptos_use_css_var::use_css_var;
#[component]
fn Demo() -> impl IntoView {
let (color, set_color) = use_css_var("--color");
set_color.set("red".to_string());
view! { }
}
The variable name itself can be a Signal.
use leptos::prelude::*;
use leptos_use_css_var::use_css_var;
#[component]
fn Demo() -> impl IntoView {
let (key, set_key) = signal("--color".to_string());
let (color, set_color) = use_css_var(key);
view! { }
}
You can specify the element that the variable is applied to as well as an initial value in case the variable is not set yet. The option to listen for changes to the variable is also available.
use leptos::prelude::*;
use leptos::html::Div;
use leptos_use_css_var::{use_css_var_with_options, UseCssVarOptions};
#[component]
fn Demo() -> impl IntoView {
let el = NodeRef::<Div>::new();
let (color, set_color) = use_css_var_with_options(
"--color",
UseCssVarOptions::default()
.target(el)
.initial_value("#eee")
.observe(true),
);
view! {
<div node_ref=el>"..."</div>
}
}
Server-Side Rendering
Make sure you follow the instructions in Server-Side Rendering.
On the server this simply returns signal(options.initial_value).
Installation
cargo add leptos-use-css-var
Options
UseCssVarOptions
Options for use_css_var_with_options.
Every option is set with a builder method of the same name, e.g. UseCssVarOptions::default().target(...). See also the API docs.
target
Type: El
The target element to read the variable from and set the variable on.
Defaults to the document.documentElement.
initial_value
Type: String
The initial value of the variable before it is read. Also the default value if the variable isn’t defined on the target. Defaults to “”.
observe
Type: bool
If true use a MutationObserver to monitor variable changes. Defaults to false.