diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 99f9c4e..ef12960 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -21,6 +21,7 @@ * [Literals & Expressions](concepts/html/literals-and-expressions.md) * [Components](concepts/html/components.md) * [Components](concepts/components/README.md) + * [Internal state](concepts/components/internalstate.md) * [Properties](concepts/components/properties.md) * [Callbacks](concepts/components/callbacks.md) * [Refs](concepts/components/refs.md) diff --git a/src/concepts/components/internalstate.md b/src/concepts/components/internalstate.md new file mode 100644 index 0000000..ebb9ba4 --- /dev/null +++ b/src/concepts/components/internalstate.md @@ -0,0 +1,86 @@ +--- +description: A component can maintain its own state and render information depending on it +--- + +# Internal state + +The component can manage it's own state using a struct that implement the trait `Component`. The HTML rendering is based on this state. +When the state change the component might be re-rendered. + +```rust +use yew::prelude::*; + +pub struct InternalStateComponent { + name:String, +} + +impl Component for InternalStateComponent { + type Message = (); + type Properties = (); + + fn create(_props: Self::Properties, _link: ComponentLink) -> Self { + Self { + name: "Clark".into(), + } + } + + fn update(&mut self, _msg: Self::Message) -> ShouldRender { + false + } + + fn change(&mut self, _props: Self::Properties) -> ShouldRender { + false + } + + fn view(&self) -> Html { + html! { + <> +

{format!("Hello {}",self.name)}

+ + } + } +} +``` + +## Defining state + +Here we add the `name` field to the struct + +```rust +// ... +pub struct InternalStateComponent { + name:String, +} +// ... +``` + +## State initialization + +The component lifecycle will initialize the state in the `create` method. + +```rust +// ... + fn create(_props: Self::Properties, _link: ComponentLink) -> Self { + Self { + name: "Clark".into(), + } + } +// ... +``` + +## Rendering using the state + +Using the `html!` macro we can render html using the state from the `view` method + +> please refer to the `html!` macro documentation page for more detail on how to render components as HTML + +```rust +// ... + fn view(&self) -> Html { + html! { +

{format!("Hello {}", self.name)}

+ } + } +// ... +# } +```