diff --git a/Cargo.lock b/Cargo.lock index 3cfae99c917..f22270ec263 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -493,7 +493,6 @@ dependencies = [ name = "contexts" version = "0.1.0" dependencies = [ - "serde", "yew", "yew-agent", ] diff --git a/packages/yew/src/functional/hooks/use_context.rs b/packages/yew/src/functional/hooks/use_context.rs index c85cadfa521..9310192fbf1 100644 --- a/packages/yew/src/functional/hooks/use_context.rs +++ b/packages/yew/src/functional/hooks/use_context.rs @@ -11,7 +11,7 @@ use crate::functional::{Hook, HookContext}; /// is returned. A component which calls `use_context` will re-render when the data of the context /// changes. /// -/// More information about contexts and how to define and consume them can be found on [Yew Docs](https://yew.rs). +/// More information about contexts and how to define and consume them can be found on [Yew Docs](https://yew.rs/docs/concepts/contexts). /// /// # Example /// diff --git a/website/docs/concepts/contexts.mdx b/website/docs/concepts/contexts.mdx index 230f8daa6c4..bbe65f7f3c1 100644 --- a/website/docs/concepts/contexts.mdx +++ b/website/docs/concepts/contexts.mdx @@ -96,35 +96,57 @@ A context provider is required to consume the context. `ContextProvider`, whe The children are re-rendered when the context changes. A struct is used to define what data is to be passed. The `ContextProvider` can be used as: ```rust -use std::rc::Rc; use yew::prelude::*; + +/// App theme #[derive(Clone, Debug, PartialEq)] struct Theme { foreground: String, background: String, } +/// Main component #[function_component] -fn NavButton() -> Html { - let theme = use_context::(); +pub fn App() -> Html { + let ctx = use_state(|| Theme { + foreground: "#000000".to_owned(), + background: "#eeeeee".to_owned(), + }); html! { - // use theme + // `ctx` is type `Rc>` while we need `Theme` + // so we deref it. + // It derefs to `&Theme`, hence the clone + context={(*ctx).clone()}> + // Every child here and their children will have access to this context. + + > } } +/// The toolbar. +/// This component has access to the context #[function_component] -fn App() -> Html { - let theme = use_memo((), |_| Theme { - foreground: "yellow".to_owned(), - background: "pink".to_owned(), - }); +pub fn Toolbar() -> Html { + html! { +
+ +
+ } +} + +/// Button placed in `Toolbar`. +/// As this component is a child of `ThemeContextProvider` in the component tree, it also has access +/// to the context. +#[function_component] +pub fn ThemedButton() -> Html { + let theme = use_context::().expect("no ctx found"); html! { - > context={theme}> - - >> + } } ```