1

How do I correctly pass an argument to an onclick event handler in a yew function component?

What I have:

#[function_component(Calculator)]
pub fn calulator() -> Html {
    let navigator = use_navigator().unwrap();
    let handle_formula_click = Callback::from(move |_| {
        navigator.push(&AppRoute::Formula { id })
    });

    html! {
            <div>
                ...
                <button onclick={handle_formula_click}>
                    ...
                </button>
                ...
            </div>
    }
}

I would like to pass in a string to the handle_formula_click callback

What I want:

#[function_component(Calculator)]
pub fn calulator() -> Html {
    let navigator = use_navigator().unwrap();
    let handle_formula_click = Callback::from(move |id: String| {
        navigator.push(&AppRoute::Formula { id })
    });

    html! {
            <div>
                ...
                <button onclick={handle_formula_click("fixed1"}>
                    ...
                </button>
                ...
            </div>
    }
}
Jon Ham
  • 11
  • 3

1 Answers1

4

You can do the following:

<button onclick={ move |_|{ handle_formula_click.emit("fixed1");}}>

vinica_boy
  • 41
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 02 '22 at 11:07