yew/website/docs/concepts/contexts.mdx
Julius Lungys 636692507e
Convert components concept docs from SC to FC (#2434)
* Convert components concept docs from SC to FC
- moved struct components to advanced topics
- added docs about HOC for Suspense and Context
- added a ease-in topic before components that introduces
HTML/CSS/JS in yew
- edit components concept to use function components

* translations

* fix todo links

* fix tests

* spelling bee
2022-02-07 11:03:12 +02:00

102 lines
2.5 KiB
Plaintext

---
title: "Contexts"
sidebar_label: Contexts
description: "Using contexts to pass data within application"
---
Generally data is passed down the component tree using props but that becomes tedious for values such as
user preferences, authentication information etc. Consider the following example which passes down the
theme using props:
```rust
use yew::{html, Children, Component, Context, Html, Properties, function_component};
#[derive(Clone, PartialEq)]
pub struct Theme {
foreground: String,
background: String,
}
#[derive(PartialEq, Properties)]
pub struct NavbarProps {
theme: Theme,
}
#[function_component]
fn Navbar(props: &NavbarProps) -> Html {
html! {
<div>
<Title theme={props.theme.clone()}>
{ "App title" }
</Title>
<NavButton theme={props.theme.clone()}>
{ "Somewhere" }
</NavButton>
</div>
}
}
#[derive(PartialEq, Properties)]
pub struct ThemeProps {
theme: Theme,
children: Children,
}
#[function_component]
fn Title(_props: &ThemeProps) -> Html {
html! {
// impl
}
}
#[function_component]
fn NavButton(_props: &ThemeProps) -> Html {
html! {
// impl
}
}
// root
let theme = Theme {
foreground: "yellow".to_owned(),
background: "pink".to_owned(),
};
html! {
<Navbar {theme} />
};
```
Passing down data like this isn't ideal for something like a theme which needs to be available everywhere.
This is where contexts come in.
Contexts can be understood as a global-ish opt in props.
You need to provide the value somewhere in the component tree and all sub-components will be able to listen into its value and changes.
## Using Contexts
In order to use contexts, we need a struct which defines what data is to be passed.
For the above use-case, consider the following struct:
```rust
#[derive(Clone, Debug, PartialEq)]
struct Theme {
foreground: String,
background: String,
}
```
A context provider is required to consume the context. `ContextProvider<T>`, where `T` is the context struct is used as the provider.
`T` must implement `Clone` and `PartialEq`. `ContextProvider` is the component whose children will have the context available to them.
The children are re-rendered when the context changes.
### Consuming context
#### Struct components
Use [HOC](../advanced-topics/struct-components/hoc)
#### Function components
`use_context` hook is used to consume contexts in function components.
See [docs for use_context](function-components/hooks/use-context) to learn more.