-
I am following the example, I am trying to pass an optional callback to the button:
I think expectedly it does not work. It seems I found a solution in leptos_dom sources, but is it the right way to do it?
|
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 5 replies
-
Your second option looks to me like it should work. Does it? |
Beta Was this translation helpful? Give feedback.
-
For optional callback properties I like to use pub struct MouseEventFn(Box<dyn Fn(MouseEvent) + 'static>);
impl<T> From<T> for MouseEventFn where T: Fn(MouseEvent) + 'static {
fn from(value: T) -> Self {
Self(Box::new(value))
}
}
impl MouseEventFn {
pub fn into_inner(self) -> Box<dyn Fn(MouseEvent) + 'static> {
self.0
}
}
#[component]
pub fn Button(
#[prop(default = ButtonType::Button)] type_: ButtonType,
#[prop(default = ButtonVariant::Primary)] variant: ButtonVariant,
#[prop(optional, into)] on_click: Option<MouseEventFn>,
children: Children,
) -> impl IntoView {
let cls = format!("btn {}", variant.to_str());
view! {
<button class={cls} type={type_.to_str()}>{children()}</button>
}.optional_event(ev::click, on_click.map(MouseEventFn::into_inner))
} This does introduce another type and also using the callback now requires view! {
<Button on_click=|e| leptos::log!("Click Event: {e:?}")>
"Button with callback"
</Button>
<Button>
"Button without a callback"
</Button>
} This is because Note that calling
This is why I am introducing the type |
Beta Was this translation helpful? Give feedback.
-
Did you know that I pushed a recent You can look at https://github.com/leptos-rs/leptos/blob/main/leptos_dom/src/callback.rs I don't know what you can't see it in the |
Beta Was this translation helpful? Give feedback.
-
Oh it's very complete now ! |
Beta Was this translation helpful? Give feedback.
-
The will be a chapter on it in the docs soon |
Beta Was this translation helpful? Give feedback.
Your second option looks to me like it should work. Does it?