1
0

context.rs 1.6 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_web::WebsysRenderer;
  15. fn main() {
  16. wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
  17. console_error_panic_hook::set_once();
  18. wasm_bindgen_futures::spawn_local(WebsysRenderer::start(Example));
  19. }
  20. #[derive(Debug)]
  21. struct CustomContext([&'static str; 3]);
  22. static Example: FC<()> = |ctx, props| {
  23. ctx.use_create_context(|| CustomContext(["Jack", "Jill", "Bob"]));
  24. ctx.render(rsx! {
  25. div {
  26. class: "py-12 px-4 text-center w-full max-w-2xl mx-auto"
  27. span {
  28. class: "text-sm font-semibold"
  29. "Dioxus Example: Jack and Jill"
  30. }
  31. h2 {
  32. class: "text-5xl mt-2 mb-6 leading-tight font-semibold font-heading"
  33. "Hello"
  34. }
  35. CustomButton { id: 0 }
  36. CustomButton { id: 1 }
  37. CustomButton { id: 2 }
  38. }
  39. })
  40. };
  41. #[derive(Props, PartialEq)]
  42. struct ButtonProps {
  43. id: u8,
  44. }
  45. fn CustomButton(ctx: Context, props: &ButtonProps) -> DomTree {
  46. let names = ctx.use_context::<CustomContext>();
  47. let name = names.0[props.id as usize];
  48. ctx.render(rsx!{
  49. button {
  50. class: "inline-block py-4 px-8 mr-6 leading-none text-white bg-indigo-600 hover:bg-indigo-900 font-semibold rounded shadow"
  51. "{name}"
  52. }
  53. })
  54. }