Higher Order Components

There are several cases where Struct components dont directly support a feature (ex. Suspense) or require a lot of boiler plate to use the features (ex. Context).

In those cases it is recommended to create function components that are higher order components.

Higher Order Components Definition

Higher Order Components are components that dont add any new Html and only wrap some other component to provide extra functionality.

Example

Hook into Context and pass it down to a struct component

  1. use yew::prelude::*;
  2. #[derive(Clone, Debug, PartialEq)]
  3. struct Theme {
  4. foreground: String,
  5. background: String,
  6. }
  7. #[function_component]
  8. pub fn App() -> Html {
  9. let ctx = use_state(|| Theme {
  10. foreground: "#000000".to_owned(),
  11. background: "#eeeeee".to_owned(),
  12. });
  13. html! {
  14. <ContextProvider<Theme> context={(*ctx).clone()}>
  15. <ThemedButtonHOC />
  16. </ContextProvider<Theme>>
  17. }
  18. }
  19. #[function_component]
  20. pub fn ThemedButtonHOC() -> Html {
  21. let theme = use_context::<Theme>().expect("no ctx found");
  22. html! {<ThemedButtonStructComponent {theme} />}
  23. }
  24. #[derive(Properties, PartialEq)]
  25. pub struct Props {
  26. pub theme: Theme,
  27. }
  28. struct ThemedButtonStructComponent;
  29. impl Component for ThemedButtonStructComponent {
  30. type Message = ();
  31. type Properties = Props;
  32. fn create(_ctx: &Context<Self>) -> Self {
  33. Self
  34. }
  35. fn view(&self, ctx: &Context<Self>) -> Html {
  36. let theme = &ctx.props().theme;
  37. html! {
  38. <button style={format!(
  39. "background: {}; color: {};",
  40. theme.background,
  41. theme.foreground
  42. )}
  43. >
  44. { "Click me!" }
  45. </button>
  46. }
  47. }
  48. }