1
0

context.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //! Example: Context API
  2. //! --------------------
  3. //! This example demonstrates how to use the raw context api for sharing state throughout the VirtualDOM Tree.
  4. //! A custom context must be its own unique type - otherwise use_context will fail. A context may be c
  5. //!
  6. //!
  7. //!
  8. //!
  9. //!
  10. //!
  11. //!
  12. //!
  13. use dioxus_core::prelude::*;
  14. use dioxus_core as dioxus;
  15. use dioxus_web::WebsysRenderer;
  16. use dioxus_html as dioxus_elements;
  17. fn main() {
  18. wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
  19. console_error_panic_hook::set_once();
  20. wasm_bindgen_futures::spawn_local(WebsysRenderer::start(Example));
  21. }
  22. #[derive(Debug)]
  23. struct CustomContext([&'static str; 3]);
  24. static Example: FC<()> = |cx| {
  25. cx.use_create_context(|| CustomContext(["Jack", "Jill", "Bob"]));
  26. cx.render(rsx! {
  27. div {
  28. class: "py-12 px-4 text-center w-full max-w-2xl mx-auto"
  29. span {
  30. class: "text-sm font-semibold"
  31. "Dioxus Example: Jack and Jill"
  32. }
  33. h2 {
  34. class: "text-5xl mt-2 mb-6 leading-tight font-semibold font-heading"
  35. "Hello"
  36. }
  37. CustomButton { id: 0 }
  38. CustomButton { id: 1 }
  39. CustomButton { id: 2 }
  40. }
  41. })
  42. };
  43. #[derive(Props, PartialEq)]
  44. struct ButtonProps {
  45. id: u8,
  46. }
  47. fn CustomButton(cx: Context<ButtonProps>) -> VNode {
  48. let names = cx.use_context::<CustomContext>();
  49. let name = names.0[cx.id as usize];
  50. cx.render(rsx!{
  51. button {
  52. class: "inline-block py-4 px-8 mr-6 leading-none text-white bg-indigo-600 hover:bg-indigo-900 font-semibold rounded shadow"
  53. "{name}"
  54. }
  55. })
  56. }