rsx_usage.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. //! A tour of the rsx! macro
  2. //! ------------------------
  3. //!
  4. //! This example serves as an informal quick reference of all the things that the rsx! macro can do.
  5. //!
  6. //! A full in-depth reference guide is available at: https://www.notion.so/rsx-macro-basics-ef6e367dec124f4784e736d91b0d0b19
  7. //!
  8. //! ### Elements
  9. //! - Create any element from its tag
  10. //! - Accept compile-safe attributes for each tag
  11. //! - Display documentation for elements
  12. //! - Arguments instead of String
  13. //! - Text
  14. //! - Inline Styles
  15. //!
  16. //! ## General Concepts
  17. //! - Iterators
  18. //! - Keys
  19. //! - Match statements
  20. //! - Conditional Rendering
  21. //!
  22. //! ### Events
  23. //! - Handle events with the "onXYZ" syntax
  24. //! - Closures can capture their environment with the 'a lifetime
  25. //!
  26. //!
  27. //! ### Components
  28. //! - Components can be made by specifying the name
  29. //! - Components can be referenced by path
  30. //! - Components may have optional parameters
  31. //! - Components may have their properties specified by spread syntax
  32. //! - Components may accept child nodes
  33. //! - Components that accept "onXYZ" get those closures bump allocated
  34. //!
  35. //! ### Fragments
  36. //! - Allow fragments using the built-in `Fragment` component
  37. //! - Accept a list of vnodes as children for a Fragment component
  38. //! - Allow keyed fragments in iterators
  39. //! - Allow top-level fragments
  40. //!
  41. fn main() {
  42. dioxus::desktop::launch(Example, |c| c);
  43. }
  44. /// When trying to return "nothing" to Dioxus, you'll need to specify the type parameter or Rust will be sad.
  45. /// This type alias specifices the type for you so you don't need to write "None as Option<()>"
  46. const NONE_ELEMENT: Option<()> = None;
  47. use baller::Baller;
  48. use dioxus::prelude::*;
  49. pub static Example: FC<()> = |cx| {
  50. let formatting = "formatting!";
  51. let formatting_tuple = ("a", "b");
  52. let lazy_fmt = format_args!("lazily formatted text");
  53. cx.render(rsx! {
  54. div {
  55. // Elements
  56. div {}
  57. h1 {"Some text"}
  58. h1 {"Some text with {formatting}"}
  59. h1 {"Formatting basic expressions {formatting_tuple.0} and {formatting_tuple.1}"}
  60. h2 {
  61. "Multiple"
  62. "Text"
  63. "Blocks"
  64. "Use comments as separators in html"
  65. }
  66. div {
  67. h1 {"multiple"}
  68. h2 {"nested"}
  69. h3 {"elements"}
  70. }
  71. div {
  72. class: "my special div"
  73. h1 {"Headers and attributes!"}
  74. }
  75. div {
  76. // pass simple rust expressions in
  77. class: lazy_fmt,
  78. id: format_args!("attributes can be passed lazily with std::fmt::Arguments"),
  79. div {
  80. class: {
  81. const WORD: &str = "expressions";
  82. format_args!("Arguments can be passed in through curly braces for complex {}", WORD)
  83. }
  84. }
  85. }
  86. // Expressions can be used in element position too:
  87. {rsx!(p { "More templating!" })}
  88. // {html!(<p>"Even HTML templating!!"</p>)}
  89. // Iterators
  90. {(0..10).map(|i| rsx!(li { "{i}" }))}
  91. {{
  92. let data = std::collections::HashMap::<&'static str, &'static str>::new();
  93. // Iterators *should* have keys when you can provide them.
  94. // Keys make your app run faster. Make sure your keys are stable, unique, and predictable.
  95. // Using an "ID" associated with your data is a good idea.
  96. data.into_iter().map(|(k, v)| rsx!(li { key: "{k}" "{v}" }))
  97. }}
  98. // Matching
  99. // Matching will throw a Rust error about "no two closures are the same type"
  100. // To fix this, call "render" method or use the "in" syntax to produce VNodes.
  101. // There's nothing we can do about it, sorry :/ (unless you want *really* unhygenic macros)
  102. {match true {
  103. true => rsx!(in cx, h1 {"Top text"}),
  104. false => cx.render(rsx!( h1 {"Bottom text"}))
  105. }}
  106. // Conditional rendering
  107. // Dioxus conditional rendering is based around None/Some. We have no special syntax for conditionals.
  108. // You can convert a bool condition to rsx! with .then and .or
  109. {true.then(|| rsx!(div {}))}
  110. // True conditions need to be rendered (same reasons as matching)
  111. {if true {
  112. rsx!(in cx, h1 {"Top text"})
  113. } else {
  114. rsx!(in cx, h1 {"Bottom text"})
  115. }}
  116. // returning "None" is a bit noisy... but rare in practice
  117. {None as Option<()>}
  118. // Use the Dioxus type-alias for less noise
  119. {NONE_ELEMENT}
  120. // can also just use empty fragments
  121. Fragment {}
  122. // Fragments let you insert groups of nodes without a parent.
  123. // This lets you make components that insert elements as siblings without a container.
  124. div {"A"}
  125. Fragment {
  126. div {"B"}
  127. div {"C"}
  128. Fragment {
  129. "D"
  130. Fragment {
  131. "heavily nested fragments is an antipattern"
  132. "they cause Dioxus to do unnecessary work"
  133. "don't use them carelessly if you can help it"
  134. }
  135. }
  136. }
  137. // Components
  138. // Can accept any paths
  139. // Notice how you still get syntax highlighting and IDE support :)
  140. Baller {}
  141. baller::Baller { }
  142. crate::baller::Baller {}
  143. // Can take properties
  144. Taller { a: "asd" }
  145. // Can take optional properties
  146. Taller { a: "asd" }
  147. // Can pass in props directly as an expression
  148. {{
  149. let props = TallerProps {a: "hello"};
  150. rsx!(Taller { ..props })
  151. }}
  152. // Spreading can also be overridden manually
  153. Taller {
  154. ..TallerProps { a: "ballin!" }
  155. a: "not ballin!"
  156. }
  157. // Can take children too!
  158. Taller { a: "asd", div {"hello world!"} }
  159. }
  160. })
  161. };
  162. mod baller {
  163. use super::*;
  164. pub struct BallerProps {}
  165. /// This component totally balls
  166. pub fn Baller(cx: Context<()>) -> VNode {
  167. todo!()
  168. }
  169. }
  170. #[derive(Debug, PartialEq, Props)]
  171. pub struct TallerProps {
  172. a: &'static str,
  173. }
  174. /// This component is taller than most :)
  175. pub fn Taller(cx: Context<TallerProps>) -> VNode {
  176. let b = true;
  177. todo!()
  178. }