description |
---|
Component can maintain it's own state and render information depending on it |
The component can manage it's own state using the Rust struct that implement the trait Component
. The HTML rendering is based on this state.
When state change there is possibility to re-render the component.
TODO documentation on state mutation
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 {
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
true
}
fn view(&self) -> Html {
html! {
<>
<h1>{format!("Hello {}",self.name)}</h1>
</>
}
}
}
Here we add the name
field in the struct
# 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 {
# true
# }
#
# fn change(&mut self, _props: Self::Properties) -> ShouldRender {
# true
# }
#
# fn view(&self) -> Html {
# html! {
# <>
# <h1>{format!("Hello {}",self.name)}</h1>
# </>
# }
# }
# }
The component lifecycle will initialize the state in the create
method.
# 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 {
# true
# }
#
# fn change(&mut self, _props: Self::Properties) -> ShouldRender {
# true
# }
#
# fn view(&self) -> Html {
# html! {
# <>
# <h1>{format!("Hello {}",self.name)}</h1>
# </>
# }
# }
# }
Using the html!
macro we can render html based on the component state in the view
method
please refer to the
html!
macro documentation page for more detail on the HTML rendering
# 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 {
# true
# }
#
# fn change(&mut self, _props: Self::Properties) -> ShouldRender {
# true
# }
#
// ...
fn view(&self) -> Html {
html! {
<>
<h1>{format!("Hello {}",self.name)}</h1>
</>
}
}
// ...
# }