optional_props.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //! Optional props
  2. //!
  3. //! This example demonstrates how to use optional props in your components. The `Button` component has several props,
  4. //! and we use a variety of attributes to set them.
  5. use dioxus::prelude::*;
  6. fn main() {
  7. dioxus::launch(app);
  8. }
  9. fn app() -> Element {
  10. rsx! {
  11. // We can set some of the props, and the rest will be filled with their default values
  12. // By default `c` can take a `None` value, but `d` is required to wrap a `Some` value
  13. Button {
  14. a: "asd".to_string(),
  15. // b can be omitted, and it will be filled with its default value
  16. c: "asd".to_string(),
  17. d: Some("asd".to_string()),
  18. e: Some("asd".to_string()),
  19. }
  20. Button {
  21. a: "asd".to_string(),
  22. b: "asd".to_string(),
  23. // We can omit the `Some` on `c` since Dioxus automatically transforms Option<T> into optional
  24. c: "asd".to_string(),
  25. d: Some("asd".to_string()),
  26. e: "asd".to_string(),
  27. }
  28. // `b` and `e` are omitted
  29. Button {
  30. a: "asd".to_string(),
  31. c: "asd".to_string(),
  32. d: Some("asd".to_string()),
  33. }
  34. }
  35. }
  36. #[derive(Props, PartialEq, Clone)]
  37. struct ButtonProps {
  38. a: String,
  39. #[props(default)]
  40. b: String,
  41. c: Option<String>,
  42. #[props(!optional)]
  43. d: Option<String>,
  44. #[props(optional)]
  45. e: SthElse<String>,
  46. }
  47. type SthElse<T> = Option<T>;
  48. #[allow(non_snake_case)]
  49. fn Button(props: ButtonProps) -> Element {
  50. rsx! {
  51. button {
  52. "{props.a} | "
  53. "{props.b:?} | "
  54. "{props.c:?} | "
  55. "{props.d:?} | "
  56. "{props.e:?}"
  57. }
  58. }
  59. }