Skip to content
This repository has been archived by the owner on Jul 19, 2020. It is now read-only.

2/8 add internal state page #83

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
86 changes: 86 additions & 0 deletions src/concepts/components/internalstate.md
Original file line number Diff line number Diff line change
@@ -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 {
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! {
<>
<h1>{format!("Hello {}",self.name)}</h1>
</>
}
}
}
```

## 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 {
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! {
<h1>{format!("Hello {}", self.name)}</h1>
}
}
// ...
# }
```