Components
Basic
Any type that implements Component
can be used in the html!
macro:
use yew::html;
html! {
<>
// No properties
<MyComponent />
// With Properties
<MyComponent prop1="lorem" prop2="ipsum" />
// With the whole set of props provided at once
<MyComponent with props />
</>
}
Nested
Components can be passed children if they have a children
field in their Properties
.
parent.rs
use yew::html;
html! {
<Container id="container">
<h4>{ "Hi" }</h4>
<div>{ "Hello" }</div>
</Container>
}
When using the with props
syntax, the children passed in the html!
macro overwrite the ones already present in the props.
use yew::{html, props, Children};
let props = yew::props!(Container::Properties {
id: "container-2",
children: Children::default(),
});
html! {
<Container with props>
// props.children will be overwritten with this
<span>{ "I am a child, as you can see" }</span>
</Container>
}
Here's the implementation of Container
:
use yew::{html, Children, Component, Html, Properties};
#[derive(Properties, Clone)]
pub struct Props {
pub id: String,
pub children: Children,
}
pub struct Container(Props);
impl Component for Container {
type Properties = Props;
// ...
fn view(&self) -> Html {
html! {
<div id=self.0.id.clone()>
{ self.0.children.clone() }
</div>
}
}
}
Nested Children with Props
Nested component properties can be accessed and mutated if the containing component types its children. In the following example, the List
component can wrap ListItem
components. For a real world example of this pattern, check out the yew-router
source code. For a more advanced example, check out the nested-list
example in the main yew repository.
use yew::html;
html! {
<List>
<ListItem value="a" />
<ListItem value="b" />
<ListItem value="c" />
</List>
}
use yew::{html, ChildrenWithProps, Component, Html, Properties};
#[derive(Properties, Clone)]
pub struct Props {
pub children: ChildrenWithProps<ListItem>,
}
pub struct List(Props);
impl Component for List {
type Properties = Props;
// ...
fn view(&self) -> Html {
html!{{
for self.0.children.iter().map(|mut item| {
item.props.value = format!("item-{}", item.props.value);
item
})
}}
}
}