| Crates.io | leptos-maybe-callback |
| lib.rs | leptos-maybe-callback |
| version | 0.2.0 |
| created_at | 2025-01-05 18:51:00.831926+00 |
| updated_at | 2025-05-05 09:27:19.616233+00 |
| description | Optional callbacks for Leptos. |
| homepage | |
| repository | https://github.com/RustForWeb/leptos-utils |
| max_upload_size | |
| id | 1504981 |
| size | 66,632 |
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>
}
}
CallbackAlternatively, 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.