conditional_rendering.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //! Example: Conditional Rendering
  2. //! ------------------------------
  3. //!
  4. //! This example shows how to hide or show elements using conditional rendering.
  5. //!
  6. //! Often times you might want to display a different UI given some sort of condition. This is called "conditonal rendering".
  7. //! In Dioxus, you can perform conditional rendering with optionals or matching.
  8. //!
  9. //! The rsx! and html! macro accepts anything that is `IntoIter<Item = impl IntoVnode>`. Options and Results both implement
  10. //! IntoIter for impl VNode, so you can use option/result for conditional rendering.
  11. use dioxus::prelude::*;
  12. fn main() {}
  13. // Convert a boolean conditional into a hide/show
  14. #[derive(PartialEq, Props)]
  15. struct MyProps {
  16. should_show: bool,
  17. }
  18. static Example: FC<MyProps> = |cx| {
  19. cx.render(rsx! {
  20. div {
  21. {cx.should_show.then(|| rsx!{
  22. h1 { "showing the title!" }
  23. })}
  24. }
  25. })
  26. };
  27. // Convert a boolean conditional into an either/or
  28. // Because rsx! is lazy (produces a closure), we cannot use it in two branch arms. To use it in matching/branching, we
  29. // must render it.
  30. //
  31. // Dioxus will let you render any `LazyNodes` into a `VNode` with `cx.render`. `rsx!` also supports the `in cx` syntax
  32. // which will do essentially the same thing as `cx.render`.
  33. //
  34. // In short:
  35. // `rsx!(in cx, ...)` is shorthand for `cx.render(rsx!(...))`
  36. #[derive(PartialEq, Props)]
  37. struct MyProps1 {
  38. should_show: bool,
  39. }
  40. static Example1: FC<MyProps1> = |cx| {
  41. cx.render(rsx! {
  42. div {
  43. // With matching
  44. {match cx.should_show {
  45. true => cx.render(rsx!(div {"it is true!"})),
  46. false => rsx!(in cx, div {"it is false!"}),
  47. }}
  48. // or with just regular conditions
  49. {if cx.should_show {
  50. rsx!(in cx, div {"it is true!"})
  51. } else {
  52. rsx!(in cx, div {"it is false!"})
  53. }}
  54. // or with optional chaining
  55. {
  56. cx.should_show
  57. .then(|| rsx!(in cx, div {"it is false!"}))
  58. .unwrap_or_else(|| rsx!(in cx, div {"it is false!"}))
  59. }
  60. }
  61. })
  62. };
  63. /// Matching can be expanded
  64. #[derive(PartialEq)]
  65. enum Color {
  66. Green,
  67. Yellow,
  68. Red,
  69. }
  70. #[derive(PartialEq, Props)]
  71. struct MyProps2 {
  72. color: Color,
  73. }
  74. static Example2: FC<MyProps2> = |cx| {
  75. cx.render(rsx! {
  76. div {
  77. {match cx.color {
  78. Color::Green => rsx!(in cx, div {"it is Green!"}),
  79. Color::Yellow => rsx!(in cx, div {"it is Yellow!"}),
  80. Color::Red => rsx!(in cx, div {"it is Red!"}),
  81. }}
  82. }
  83. })
  84. };