rsx_usage.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #![allow(non_snake_case)]
  2. //! A tour of the rsx! macro
  3. //! ------------------------
  4. //!
  5. //! This example serves as an informal quick reference of all the things that the rsx! macro can do.
  6. //!
  7. //! A full in-depth reference guide is available at: https://www.notion.so/rsx-macro-basics-ef6e367dec124f4784e736d91b0d0b19
  8. //!
  9. //! ### Elements
  10. //! - Create any element from its tag
  11. //! - Accept compile-safe attributes for each tag
  12. //! - Display documentation for elements
  13. //! - Arguments instead of String
  14. //! - Text
  15. //! - Inline Styles
  16. //!
  17. //! ## General Concepts
  18. //! - Iterators
  19. //! - Keys
  20. //! - Match statements
  21. //! - Conditional Rendering
  22. //!
  23. //! ### Events
  24. //! - Handle events with the "onXYZ" syntax
  25. //! - Closures can capture their environment with the 'a lifetime
  26. //!
  27. //!
  28. //! ### Components
  29. //! - Components can be made by specifying the name
  30. //! - Components can be referenced by path
  31. //! - Components may have optional parameters
  32. //! - Components may have their properties specified by spread syntax
  33. //! - Components may accept child nodes
  34. //! - Components that accept "onXYZ" get those closures bump allocated
  35. //!
  36. //! ### Fragments
  37. //! - Allow fragments using the built-in `Fragment` component
  38. //! - Accept a list of vnodes as children for a Fragment component
  39. //! - Allow keyed fragments in iterators
  40. //! - Allow top-level fragments
  41. //!
  42. fn main() {
  43. dioxus_desktop::launch(app);
  44. }
  45. use core::{fmt, str::FromStr};
  46. use std::fmt::Display;
  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. // can also just use empty fragments
  123. Fragment {}
  124. // Fragments let you insert groups of nodes without a parent.
  125. // This lets you make components that insert elements as siblings without a container.
  126. div {"A"}
  127. Fragment {
  128. div {"B"}
  129. div {"C"}
  130. Fragment {
  131. "D"
  132. Fragment {
  133. "E"
  134. "F"
  135. }
  136. }
  137. }
  138. // Components
  139. // Can accept any paths
  140. // Notice how you still get syntax highlighting and IDE support :)
  141. Baller {}
  142. baller::Baller {}
  143. crate::baller::Baller {}
  144. // Can take properties
  145. Taller { a: "asd" }
  146. // Can take optional properties
  147. Taller { a: "asd" }
  148. // Can pass in props directly as an expression
  149. {
  150. let props = TallerProps {a: "hello", children: Default::default()};
  151. rsx!(Taller { ..props })
  152. }
  153. // Spreading can also be overridden manually
  154. Taller {
  155. ..TallerProps { a: "ballin!", children: Default::default() },
  156. a: "not ballin!"
  157. }
  158. // Can take children too!
  159. Taller { a: "asd", div {"hello world!"} }
  160. // This component's props are defined *inline* with the `inline_props` macro
  161. WithInline { text: "using functionc all syntax" }
  162. // Components can be generic too
  163. // This component takes i32 type to give you typed input
  164. TypedInput::<TypedInputProps<i32>> {}
  165. // Type inference can be used too
  166. TypedInput { initial: 10.0 }
  167. // geneircs with the `inline_props` macro
  168. Label { text: "hello geneirc world!" }
  169. Label { text: 99.9 }
  170. // Lowercase components work too, as long as they are access using a path
  171. baller::lowercase_component {}
  172. // For in-scope lowercase components, use the `self` keyword
  173. self::lowercase_helper {}
  174. // helper functions
  175. // Anything that implements IntoVnode can be dropped directly into Rsx
  176. helper(&cx, "hello world!")
  177. // Strings can be supplied directly
  178. String::from("Hello world!")
  179. // So can format_args
  180. format_args!("Hello {}!", "world")
  181. // Or we can shell out to a helper function
  182. format_dollars(10, 50)
  183. }
  184. })
  185. }
  186. fn format_dollars(dollars: u32, cents: u32) -> String {
  187. format!("${}.{:02}", dollars, cents)
  188. }
  189. fn helper<'a>(cx: &'a ScopeState, text: &str) -> Element<'a> {
  190. cx.render(rsx! {
  191. p { "{text}" }
  192. })
  193. }
  194. fn lowercase_helper(cx: Scope) -> Element {
  195. cx.render(rsx! {
  196. "asd"
  197. })
  198. }
  199. mod baller {
  200. use super::*;
  201. #[derive(Props, PartialEq, Eq)]
  202. pub struct BallerProps {}
  203. #[allow(non_snake_case)]
  204. /// This component totally balls
  205. pub fn Baller(_: Scope<BallerProps>) -> Element {
  206. todo!()
  207. }
  208. pub fn lowercase_component(cx: Scope) -> Element {
  209. cx.render(rsx! { "look ma, no uppercase" })
  210. }
  211. }
  212. #[derive(Props)]
  213. pub struct TallerProps<'a> {
  214. /// Fields are documented and accessible in rsx!
  215. a: &'static str,
  216. children: Element<'a>,
  217. }
  218. /// Documention for this component is visible within the rsx macro
  219. #[allow(non_snake_case)]
  220. pub fn Taller<'a>(cx: Scope<'a, TallerProps<'a>>) -> Element {
  221. cx.render(rsx! {
  222. &cx.props.children
  223. })
  224. }
  225. #[derive(Props, PartialEq, Eq)]
  226. pub struct TypedInputProps<T> {
  227. #[props(optional, default)]
  228. initial: Option<T>,
  229. }
  230. #[allow(non_snake_case)]
  231. pub fn TypedInput<T>(_: Scope<TypedInputProps<T>>) -> Element
  232. where
  233. T: FromStr + fmt::Display,
  234. <T as FromStr>::Err: std::fmt::Display,
  235. {
  236. todo!()
  237. }
  238. #[inline_props]
  239. fn WithInline<'a>(cx: Scope<'a>, text: &'a str) -> Element {
  240. cx.render(rsx! {
  241. p { "{text}" }
  242. })
  243. }
  244. // generic component with inline_props too
  245. #[inline_props]
  246. fn Label<T>(cx: Scope, text: T) -> Element
  247. where
  248. T: Display,
  249. {
  250. cx.render(rsx! {
  251. p { "{text}" }
  252. })
  253. }