context.rs 1.6 KB

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