Function create_context

Source
pub fn create_context<T: 'static>(init: Rc<T>) -> Context<T>
Expand description

Creates a new React context that can hold a global state.

Use ContextProvider to make the context available for its subtrees and use_context() to get access to the context value.

ยงExample

thread_local! {
  // Pass in a default value for the context.
  static THEME_CONTEXT: Context<Theme> = create_context(Theme::LightMode.into());
}

struct App;

impl Component for App {
  fn render(&self) -> VNode {
    // Use a `ContextProvider` to pass the context value to the trees below.
    // In this example, we are passing down `Theme::DarkMode`.

    ContextProvider::from(&THEME_CONTEXT)
      .value(Some(Theme::DarkMode.into()))
      .build(
        Toolbar.build(),
      )
  }
}

struct Toolbar;

impl Component for Toolbar {
  fn render(&self) -> VNode {
    // Theme context does not have to be passed down explicitly.
    h!(div).build(Button.build())
  }
}

struct Button;

impl Component for Button {
  fn render(&self) -> VNode {
    // Use the `use_context` hook to get access to the context value.
    let theme = use_context(&THEME_CONTEXT);

    h!(button)
      .style(
        &Style::new()
          .background_color(match *theme {
            Theme::LightMode => "white",
            Theme::DarkMode => "black",
          })
      )
      .build("Button")
  }
}