rsx_usage.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. fn main() {
  41. dioxus_desktop::launch(App);
  42. }
  43. use core::{fmt, str::FromStr};
  44. use std::fmt::Display;
  45. use baller::Baller;
  46. use dioxus::prelude::*;
  47. #[component]
  48. fn App(cx: Scope) -> Element {
  49. let formatting = "formatting!";
  50. let formatting_tuple = ("a", "b");
  51. let lazy_fmt = format_args!("lazily formatted text");
  52. let asd = 123;
  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. class: "asd",
  81. class: "{asd}",
  82. // if statements can be used to conditionally render attributes
  83. class: if formatting.contains("form") { "{asd}" },
  84. div {
  85. class: {
  86. const WORD: &str = "expressions";
  87. format_args!("Arguments can be passed in through curly braces for complex {WORD}")
  88. }
  89. }
  90. }
  91. // Expressions can be used in element position too:
  92. {rsx!(p { "More templating!" })},
  93. // Iterators
  94. {(0..10).map(|i| rsx!(li { "{i}" }))},
  95. // Iterators within expressions
  96. {
  97. let data = std::collections::HashMap::<&'static str, &'static str>::new();
  98. // Iterators *should* have keys when you can provide them.
  99. // Keys make your app run faster. Make sure your keys are stable, unique, and predictable.
  100. // Using an "ID" associated with your data is a good idea.
  101. data.into_iter().map(|(k, v)| rsx!(li { key: "{k}", "{v}" }))
  102. }
  103. // Matching
  104. match true {
  105. true => rsx!( h1 {"Top text"}),
  106. false => rsx!( h1 {"Bottom text"})
  107. }
  108. // Conditional rendering
  109. // Dioxus conditional rendering is based around None/Some. We have no special syntax for conditionals.
  110. // You can convert a bool condition to rsx! with .then and .or
  111. {true.then(|| rsx!(div {}))},
  112. // Alternatively, you can use the "if" syntax - but both branches must be resolve to Element
  113. if false {
  114. h1 {"Top text"}
  115. } else {
  116. h1 {"Bottom text"}
  117. }
  118. // Using optionals for diverging branches
  119. // Note that since this is wrapped in curlies, it's interpreted as an expression
  120. {if true {
  121. Some(rsx!(h1 {"Top text"}))
  122. } else {
  123. None
  124. }}
  125. // returning "None" without a diverging branch is a bit noisy... but rare in practice
  126. {None as Option<()>},
  127. // can also just use empty fragments
  128. Fragment {}
  129. // Fragments let you insert groups of nodes without a parent.
  130. // This lets you make components that insert elements as siblings without a container.
  131. div {"A"}
  132. Fragment {
  133. div {"B"}
  134. div {"C"}
  135. Fragment {
  136. "D"
  137. Fragment {
  138. "E"
  139. "F"
  140. }
  141. }
  142. }
  143. // Components
  144. // Can accept any paths
  145. // Notice how you still get syntax highlighting and IDE support :)
  146. Baller {}
  147. baller::Baller {}
  148. crate::baller::Baller {}
  149. // Can take properties
  150. Taller { a: "asd" }
  151. // Can take optional properties
  152. Taller { a: "asd" }
  153. // Can pass in props directly as an expression
  154. {
  155. let props = TallerProps {a: "hello", children: None };
  156. rsx!(Taller { ..props })
  157. }
  158. // Spreading can also be overridden manually
  159. Taller {
  160. ..TallerProps { a: "ballin!", children: None },
  161. a: "not ballin!"
  162. }
  163. // Can take children too!
  164. Taller { a: "asd", div {"hello world!"} }
  165. // This component's props are defined *inline* with the `inline_props` macro
  166. WithInline { text: "using functionc all syntax" }
  167. // Components can be generic too
  168. // This component takes i32 type to give you typed input
  169. TypedInput::<i32> {}
  170. // Type inference can be used too
  171. TypedInput { initial: 10.0 }
  172. // geneircs with the `inline_props` macro
  173. Label { text: "hello geneirc world!" }
  174. Label { text: 99.9 }
  175. // Lowercase components work too, as long as they are access using a path
  176. baller::lowercase_component {}
  177. // For in-scope lowercase components, use the `self` keyword
  178. self::lowercase_helper {}
  179. // helper functions
  180. // Anything that implements IntoVnode can be dropped directly into Rsx
  181. {helper(cx, "hello world!")}
  182. // Strings can be supplied directly
  183. {String::from("Hello world!")}
  184. // So can format_args
  185. {format_args!("Hello {}!", "world")}
  186. // Or we can shell out to a helper function
  187. {format_dollars(10, 50)}
  188. }
  189. })
  190. }
  191. fn format_dollars(dollars: u32, cents: u32) -> String {
  192. format!("${dollars}.{cents:02}")
  193. }
  194. fn helper<'a>(cx: &'a ScopeState, text: &'a str) -> Element<'a> {
  195. cx.render(rsx! {
  196. p { "{text}" }
  197. })
  198. }
  199. // no_case_check disables PascalCase checking if you *really* want a snake_case component.
  200. // This will likely be deprecated/removed in a future update that will introduce a more polished linting system,
  201. // something like Clippy.
  202. #[component(no_case_check)]
  203. fn lowercase_helper(cx: Scope) -> Element {
  204. cx.render(rsx! {
  205. "asd"
  206. })
  207. }
  208. mod baller {
  209. use super::*;
  210. #[derive(Props, PartialEq, Eq)]
  211. pub struct BallerProps {}
  212. #[component]
  213. /// This component totally balls
  214. pub fn Baller(_cx: Scope<BallerProps>) -> Element {
  215. todo!()
  216. }
  217. // no_case_check disables PascalCase checking if you *really* want a snake_case component.
  218. // This will likely be deprecated/removed in a future update that will introduce a more polished linting system,
  219. // something like Clippy.
  220. #[component(no_case_check)]
  221. pub fn lowercase_component(cx: Scope) -> Element {
  222. cx.render(rsx! { "look ma, no uppercase" })
  223. }
  224. }
  225. #[derive(Props)]
  226. pub struct TallerProps<'a> {
  227. /// Fields are documented and accessible in rsx!
  228. a: &'static str,
  229. children: Element<'a>,
  230. }
  231. /// Documention for this component is visible within the rsx macro
  232. #[component]
  233. pub fn Taller<'a>(cx: Scope<'a, TallerProps<'a>>) -> Element {
  234. cx.render(rsx! {
  235. {&cx.props.children}
  236. })
  237. }
  238. #[derive(Props, PartialEq, Eq)]
  239. pub struct TypedInputProps<T> {
  240. #[props(optional, default)]
  241. initial: Option<T>,
  242. }
  243. #[allow(non_snake_case)]
  244. pub fn TypedInput<T>(_: Scope<TypedInputProps<T>>) -> Element
  245. where
  246. T: FromStr + fmt::Display,
  247. <T as FromStr>::Err: std::fmt::Display,
  248. {
  249. todo!()
  250. }
  251. #[component]
  252. fn WithInline<'a>(cx: Scope<'a>, text: &'a str) -> Element {
  253. cx.render(rsx! {
  254. p { "{text}" }
  255. })
  256. }
  257. #[component]
  258. fn Label<T>(cx: Scope, text: T) -> Element
  259. where
  260. T: Display,
  261. {
  262. cx.render(rsx! {
  263. p { "{text}" }
  264. })
  265. }