Skip to content

Commit

Permalink
Improve Context API docs (#3409)
Browse files Browse the repository at this point in the history
* improved context API docs, added example of struct component context producer

* forgot to commit that oops
  • Loading branch information
its-the-shrimp authored Sep 23, 2023
1 parent 954b0ec commit a2786b1
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 18 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion examples/contexts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@ edition = "2021"
license = "MIT OR Apache-2.0"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
yew = { path = "../../packages/yew", features = ["csr"] }
yew-agent = { path = "../../packages/yew-agent" }
3 changes: 3 additions & 0 deletions examples/contexts/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
mod msg_ctx;
mod producer;
mod struct_component_producer;
mod struct_component_subscriber;
mod subscriber;

use msg_ctx::MessageProvider;
use producer::Producer;
use struct_component_producer::StructComponentProducer;
use struct_component_subscriber::StructComponentSubscriber;
use subscriber::Subscriber;
use yew::prelude::*;
Expand All @@ -14,6 +16,7 @@ pub fn App() -> Html {
html! {
<MessageProvider>
<Producer />
<StructComponentProducer />
<Subscriber />
<StructComponentSubscriber />
</MessageProvider>
Expand Down
4 changes: 1 addition & 3 deletions examples/contexts/src/producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ use super::msg_ctx::MessageContext;
pub fn Producer() -> Html {
let msg_ctx = use_context::<MessageContext>().unwrap();

let onclick = Callback::from(move |_| msg_ctx.dispatch("Message Received.".to_string()));

html! {
<button {onclick}>
<button onclick={move |_| msg_ctx.dispatch("Message Received.".to_string())}>
{"PRESS ME"}
</button>
}
Expand Down
27 changes: 27 additions & 0 deletions examples/contexts/src/struct_component_producer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use yew::prelude::*;

use super::msg_ctx::MessageContext;

pub struct StructComponentProducer;

impl Component for StructComponentProducer {
type Message = ();
type Properties = ();

fn create(_ctx: &Context<Self>) -> Self {
Self
}

fn view(&self, ctx: &Context<Self>) -> Html {
let (msg_ctx, _) = ctx
.link()
.context::<MessageContext>(Callback::noop())
.expect("No Message Context Provided");

html! {
<button onclick={move |_| msg_ctx.dispatch("Other message received.".to_owned())}>
{"OR ME"}
</button>
}
}
}
2 changes: 1 addition & 1 deletion packages/yew/src/functional/hooks/use_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand Down
46 changes: 34 additions & 12 deletions website/docs/concepts/contexts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -96,35 +96,57 @@ A context provider is required to consume the context. `ContextProvider<T>`, 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::<Theme>();
pub fn App() -> Html {
let ctx = use_state(|| Theme {
foreground: "#000000".to_owned(),
background: "#eeeeee".to_owned(),
});

html! {
// use theme
// `ctx` is type `Rc<UseStateHandle<Theme>>` while we need `Theme`
// so we deref it.
// It derefs to `&Theme`, hence the clone
<ContextProvider<Theme> context={(*ctx).clone()}>
// Every child here and their children will have access to this context.
<Toolbar />
</ContextProvider<Theme>>
}
}

/// 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! {
<div>
<ThemedButton />
</div>
}
}

/// 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::<Theme>().expect("no ctx found");

html! {
<ContextProvider<Rc<Theme>> context={theme}>
<NavButton />
</ContextProvider<Rc<Theme>>>
<button style={format!("background: {}; color: {};", theme.background, theme.foreground)}>
{ "Click me!" }
</button>
}
}
```
Expand Down

0 comments on commit a2786b1

Please sign in to comment.