1
0

conditional_rendering.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #![allow(unused)]
  2. #![allow(non_snake_case)]
  3. use dioxus::prelude::*;
  4. fn main() {
  5. dioxus_desktop::launch(App);
  6. }
  7. pub fn App(cx: Scope) -> Element {
  8. let is_logged_in = use_state(cx, || false);
  9. cx.render(rsx!(LogIn {
  10. is_logged_in: **is_logged_in,
  11. on_log_in: |_| is_logged_in.set(true),
  12. on_log_out: |_| is_logged_in.set(false),
  13. }))
  14. }
  15. #[inline_props]
  16. #[rustfmt::skip]
  17. fn LogIn<'a>(
  18. cx: Scope<'a>,
  19. is_logged_in: bool,
  20. on_log_in: EventHandler<'a>,
  21. on_log_out: EventHandler<'a>,
  22. ) -> Element<'a> {
  23. // ANCHOR: if_else
  24. if *is_logged_in {
  25. cx.render(rsx! {
  26. "Welcome!"
  27. button {
  28. onclick: move |_| on_log_out.call(()),
  29. "Log Out",
  30. }
  31. })
  32. } else {
  33. cx.render(rsx! {
  34. button {
  35. onclick: move |_| on_log_in.call(()),
  36. "Log In",
  37. }
  38. })
  39. }
  40. // ANCHOR_END: if_else
  41. }
  42. #[inline_props]
  43. #[rustfmt::skip]
  44. fn LogInImproved<'a>(
  45. cx: Scope<'a>,
  46. is_logged_in: bool,
  47. on_log_in: EventHandler<'a>,
  48. on_log_out: EventHandler<'a>,
  49. ) -> Element<'a> {
  50. // ANCHOR: if_else_improved
  51. cx.render(rsx! {
  52. // We only render the welcome message if we are logged in
  53. // You can use if statements in the middle of a render block to conditionally render elements
  54. if *is_logged_in {
  55. // Notice the body of this if statment is rsx code, not an expression
  56. "Welcome!"
  57. }
  58. button {
  59. // depending on the value of `is_logged_in`, we will call a different event handler
  60. onclick: move |_| if *is_logged_in {
  61. on_log_in.call(())
  62. }
  63. else{
  64. on_log_out.call(())
  65. },
  66. if *is_logged_in {
  67. // if we are logged in, the button should say "Log Out"
  68. "Log Out"
  69. } else {
  70. // if we are not logged in, the button should say "Log In"
  71. "Log In"
  72. }
  73. }
  74. })
  75. // ANCHOR_END: if_else_improved
  76. }
  77. #[inline_props]
  78. #[rustfmt::skip]
  79. fn LogInWarning(cx: Scope, is_logged_in: bool) -> Element {
  80. // ANCHOR: conditional_none
  81. if *is_logged_in {
  82. return None;
  83. }
  84. cx.render(rsx! {
  85. a {
  86. "You must be logged in to comment"
  87. }
  88. })
  89. // ANCHOR_END: conditional_none
  90. }