dioxus
dioxus copied to clipboard
Custom property defaults
Specific Demand
Reading https://dioxuslabs.com/guide/components/propsmacro.html, it does not seem possible to specify a particular default value for a property. #[props(default)] will always use the types Default implementation to infer the value.
Lets say we want the following boolean property to default to true (instead of bools default value false):
#[derive(Props, PartialEq)]
pub struct MyProps {
#[props(default)]
active: bool,
}
Did I miss something and this is already possible?
Otherwise: Is something like #[props(default(true))] possible?
Yew does that with its #[prop_or(value)] annotation (for reference: https://yew.rs/docs/concepts/components/properties).
You can use Option<bool> which defaults to None, and then you can call .unwrap_or(true) – this will give you the specified value, or true if not specified.
In my opinion, this is the most idiomatic way, because it's clear and explicit. Also, it allows for the most flexibility – you might want to use other Option methods instead. For example, you could unwrap_or_else if you want to provide a closure, or or if you want to provide another Option. However, the maintainers might also decide to add the feature you describe as part of the props, idk. For now, use unwrap_or.
Thank you! I totally missed that... That works great. Close the issue if you want.
One downside I see is that, if accessed multiple times, you either have to unwrap_or(...) at multiple locations with the same(!) value, probably with a defined constant, at least I cannot see using different defaults at different locations in a Component... Or you have to access it once with a default provider and store that value somewhere. Both options seem to add some boilerplate.
But yes, the Option route is really flexible.
Sorry, we actually do have this ability but I guess it's just not documented.
Check out the typed-builder crate where we borrow some of the proc macro code from:
https://github.com/idanarye/rust-typed-builder
This is now documented here