Skip to content

pass functions as props in dioxus 0.5 #3192

@PicoJr

Description

@PicoJr

I would like to pass closures (ideally) or functions as props.

Similar to: #1067 but the answer was specific to dioxus 0.3, and since then, the migration guide indicates:

Manual prop structs in dioxus 0.5 need to derive Clone in addition to Props and PartialEq

The compiler complains that my generic type F needs to implement PartialEq.
And I am unsure how to proceed at this point.

Steps To Reproduce

dx new
# sub-template: Web
# CSS: Vanilla (does not matter here)
# router: true (does not matter here)

Define the following component:

#[component]
fn Comp<F: Fn() + 'static>(function: F) -> Element {
    function();
    rsx! {
        div {}
    }
}

And use it like this inside the Home rsx!

    rsx! {
       // redacted
        Comp {
            function: || println!("hello world")
        }
    }

The compiler will complain that my generic type F needs to implement PartialEq:

❯ cargo build
   Compiling dx-props-fn v0.1.0 (<redacted>/dx-props-fn)
error[E0369]: binary operation `==` cannot be applied to type `&mut CompProps<F>`
  --> src/main.rs:25:1
   |
25 | #[component]
   | ^^^^^^^^^^^^
   |
   = note: this error originates in the derive macro `Props` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider further restricting this bound
   |
26 | fn Comp<F: Fn() + 'static + std::cmp::PartialEq>(function: F) -> Element {
   |                           +++++++++++++++++++++

For more information about this error, try `rustc --explain E0369`.
error: could not compile `dx-props-fn` (bin "dx-props-fn") due to 1 previous error

What I would like to do: be able to provide custom logic via my components props.

How would you proceed ?

Thanks for your time,

Best regards,

Environment:

  • Dioxus version: 0.5.6
  • Rust version: 1.79
  • OS info: Arch Linux
  • App platform: Web

relevant link for closures:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions