1
0

rsx_usage.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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(app);
  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 specifies 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. fn app(cx: Scope) -> Element {
  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. h1 {"Formatting without interpolation " [formatting_tuple.0] "and" [formatting_tuple.1] }
  61. h2 {
  62. "Multiple"
  63. "Text"
  64. "Blocks"
  65. "Use comments as separators in html"
  66. }
  67. div {
  68. h1 {"multiple"}
  69. h2 {"nested"}
  70. h3 {"elements"}
  71. }
  72. div {
  73. class: "my special div",
  74. h1 {"Headers and attributes!"}
  75. }
  76. div {
  77. // pass simple rust expressions in
  78. class: lazy_fmt,
  79. id: format_args!("attributes can be passed lazily with std::fmt::Arguments"),
  80. div {
  81. class: {
  82. const WORD: &str = "expressions";
  83. format_args!("Arguments can be passed in through curly braces for complex {}", WORD)
  84. }
  85. }
  86. }
  87. // Expressions can be used in element position too:
  88. rsx!(p { "More templating!" }),
  89. // Iterators
  90. (0..10).map(|i| rsx!(li { "{i}" })),
  91. // Iterators within expressions
  92. {
  93. let data = std::collections::HashMap::<&'static str, &'static str>::new();
  94. // Iterators *should* have keys when you can provide them.
  95. // Keys make your app run faster. Make sure your keys are stable, unique, and predictable.
  96. // Using an "ID" associated with your data is a good idea.
  97. data.into_iter().map(|(k, v)| rsx!(li { key: "{k}", "{v}" }))
  98. }
  99. // Matching
  100. match true {
  101. true => rsx!( h1 {"Top text"}),
  102. false => rsx!( h1 {"Bottom text"})
  103. }
  104. // Conditional rendering
  105. // Dioxus conditional rendering is based around None/Some. We have no special syntax for conditionals.
  106. // You can convert a bool condition to rsx! with .then and .or
  107. true.then(|| rsx!(div {})),
  108. // Alternatively, you can use the "if" syntax - but both branches must be resolve to Element
  109. if false {
  110. rsx!(h1 {"Top text"})
  111. } else {
  112. rsx!(h1 {"Bottom text"})
  113. }
  114. // Using optionals for diverging branches
  115. if true {
  116. Some(rsx!(h1 {"Top text"}))
  117. } else {
  118. None
  119. }
  120. // returning "None" without a diverging branch is a bit noisy... but rare in practice
  121. None as Option<()>,
  122. // Use the Dioxus type-alias for less noise
  123. NONE_ELEMENT,
  124. // can also just use empty fragments
  125. Fragment {}
  126. // Fragments let you insert groups of nodes without a parent.
  127. // This lets you make components that insert elements as siblings without a container.
  128. div {"A"}
  129. Fragment {
  130. div {"B"}
  131. div {"C"}
  132. Fragment {
  133. "D"
  134. Fragment {
  135. "E"
  136. "F"
  137. }
  138. }
  139. }
  140. // Components
  141. // Can accept any paths
  142. // Notice how you still get syntax highlighting and IDE support :)
  143. Baller {}
  144. baller::Baller { }
  145. crate::baller::Baller {}
  146. // Can take properties
  147. Taller { a: "asd" }
  148. // Can take optional properties
  149. Taller { a: "asd" }
  150. // Can pass in props directly as an expression
  151. {
  152. let props = TallerProps {a: "hello", children: Default::default()};
  153. rsx!(Taller { ..props })
  154. }
  155. // Spreading can also be overridden manually
  156. Taller {
  157. ..TallerProps { a: "ballin!", children: Default::default() },
  158. a: "not ballin!"
  159. }
  160. // Can take children too!
  161. Taller { a: "asd", div {"hello world!"} }
  162. // Components can be used with the `call` syntax
  163. // This component's props are defined *inline* with the `inline_props` macro
  164. with_inline(
  165. text: "using functionc all syntax"
  166. )
  167. // helper functions
  168. // Single values must be wrapped in braces or `Some` to satisfy `IntoIterator`
  169. [helper(&cx, "hello world!")]
  170. }
  171. })
  172. }
  173. fn helper<'a>(cx: &'a ScopeState, text: &str) -> Element<'a> {
  174. cx.render(rsx! {
  175. p { "{text}" }
  176. })
  177. }
  178. mod baller {
  179. use super::*;
  180. #[derive(Props, PartialEq)]
  181. pub struct BallerProps {}
  182. #[allow(non_snake_case)]
  183. /// This component totally balls
  184. pub fn Baller(_: Scope<BallerProps>) -> Element {
  185. todo!()
  186. }
  187. }
  188. #[derive(Props)]
  189. pub struct TallerProps<'a> {
  190. /// Fields are documented and accessible in rsx!
  191. a: &'static str,
  192. children: Element<'a>,
  193. }
  194. /// Documention for this component is visible within the rsx macro
  195. #[allow(non_snake_case)]
  196. pub fn Taller<'a>(cx: Scope<'a, TallerProps<'a>>) -> Element {
  197. cx.render(rsx! {
  198. &cx.props.children
  199. })
  200. }
  201. #[inline_props]
  202. fn with_inline<'a>(cx: Scope<'a>, text: &'a str) -> Element {
  203. cx.render(rsx! {
  204. p { "{text}" }
  205. })
  206. }