Crates.io | leptos-maybe-callback |
lib.rs | leptos-maybe-callback |
version | |
source | src |
created_at | 2025-01-05 18:51:00.831926+00 |
updated_at | 2025-02-10 18:54:34.790826+00 |
description | Optional callbacks for Leptos. |
homepage | |
repository | https://github.com/RustForWeb/leptos-utils |
max_upload_size | |
id | 1504981 |
Cargo.toml error: | TOML parse error at line 18, column 1 | 18 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
Optional callbacks for Leptos.
Documentation for the crate is available on Docs.rs:
Define a component that accepts an optional callback using #[prop(into, optional)]
. This allows passing a closure, a
Callback
, or omitting the prop.
use leptos::{ev::MouseEvent, prelude::*};
use leptos_maybe_callback::MaybeCallback;
/// A button component with an optional `onclick` callback.
#[component]
pub fn Button(
#[prop(into, optional)]
onclick: MaybeCallback<MouseEvent>,
) -> impl IntoView {
view! {
<button on:click=onclick.into_handler()>
"Click me"
</button>
}
}
Use the Button
component and provide a closure for the onclick
prop.
use leptos::prelude::*;
use leptos_maybe_callback::MaybeCallback;
/// Parent component using `Button` with a closure.
#[component]
pub fn ButtonWithClosure() -> impl IntoView {
view! {
<div>
<Button onclick=|_| log::info!("Clicked via closure!") />
<Button />
</div>
}
}
Callback
Alternatively, pass a Callback
as the onclick
prop.
use leptos::{ev::MouseEvent, prelude::*};
use leptos_maybe_callback::MaybeCallback;
/// Parent component using `Button` with a `Callback`.
#[component]
pub fn ButtonWithCallback() -> impl IntoView {
let on_click = Callback::new(|event: MouseEvent| {
log::info!("Clicked with event: {:?}", event);
});
view! {
<div>
<Button onclick=on_click />
<Button />
</div>
}
}
If no callback is needed, omit the onclick
prop or pass None
.
use leptos::{ev::MouseEvent, prelude::*};
use leptos_maybe_callback::MaybeCallback;
/// Parent component using `Button` without a callback.
#[component]
pub fn ButtonWithoutCallback() -> impl IntoView {
view! {
<div>
<Button />
<Button onclick={None::<Callback<MouseEvent>>} />
</div>
}
}
The Leptos Maybe Callback project is part of Rust For Web.
Rust For Web creates and ports web UI libraries for Rust. All projects are free and open source.