dioxus/packages/web/examples/context.rs
Jonathan Kelley 508c560320 Feat: massive changes to definition of components
This change switches back to the original `ctx<props>` syntax for
commponents. This lets lifetime elision to remove the need to match
exactly which lifetime (props or ctx) gets  carried to the output. As
such, `Props` is currently required to be static. It *is* possible to
loosen this restriction, and will be done in the future, though only
through adding metadata about the props through the Props derive
macro. Implementing the IS_STATIC trait is unsafe, so the derive macro
will do it through some heuristics.

For now, this unlocks sharing vnodes from parents to children, enabling
pass-thru components, fragments, portals, etc.
2021-06-01 18:33:15 -04:00

65 lines
1.6 KiB
Rust

//! Example: Context API
//! --------------------
//! This example demonstrates how to use the raw context api for sharing state throughout the VirtualDOM Tree.
//! A custom context must be its own unique type - otherwise use_context will fail. A context may be c
//!
//!
//!
//!
//!
//!
//!
//!
use dioxus_core::prelude::*;
use dioxus_web::WebsysRenderer;
fn main() {
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
console_error_panic_hook::set_once();
wasm_bindgen_futures::spawn_local(WebsysRenderer::start(Example));
}
#[derive(Debug)]
struct CustomContext([&'static str; 3]);
static Example: FC<()> = |ctx| {
ctx.use_create_context(|| CustomContext(["Jack", "Jill", "Bob"]));
ctx.render(rsx! {
div {
class: "py-12 px-4 text-center w-full max-w-2xl mx-auto"
span {
class: "text-sm font-semibold"
"Dioxus Example: Jack and Jill"
}
h2 {
class: "text-5xl mt-2 mb-6 leading-tight font-semibold font-heading"
"Hello"
}
CustomButton { id: 0 }
CustomButton { id: 1 }
CustomButton { id: 2 }
}
})
};
#[derive(Props, PartialEq)]
struct ButtonProps {
id: u8,
}
fn CustomButton(ctx: Context, props: &ButtonProps) -> VNode {
let names = ctx.use_context::<CustomContext>();
let name = names.0[ctx.id as usize];
ctx.render(rsx!{
button {
class: "inline-block py-4 px-8 mr-6 leading-none text-white bg-indigo-600 hover:bg-indigo-900 font-semibold rounded shadow"
"{name}"
}
})
}