Components

Basic

Any type that implements Component can be used in the html! macro:

  1. use yew::html;
  2. html! {
  3. <>
  4. // No properties
  5. <MyComponent />
  6. // With Properties
  7. <MyComponent prop1="lorem" prop2="ipsum" />
  8. // With the whole set of props provided at once
  9. <MyComponent with props />
  10. </>
  11. }

Nested

Components can be passed children if they have a children field in their Properties.

parent.rs

  1. use yew::html;
  2. html! {
  3. <Container id="container">
  4. <h4>{ "Hi" }</h4>
  5. <div>{ "Hello" }</div>
  6. </Container>
  7. }

When using the with props syntax, the children passed in the html! macro overwrite the ones already present in the props.

  1. use yew::{html, props, Children};
  2. let props = yew::props!(Container::Properties {
  3. id: "container-2",
  4. children: Children::default(),
  5. });
  6. html! {
  7. <Container with props>
  8. // props.children will be overwritten with this
  9. <span>{ "I am a child, as you can see" }</span>
  10. </Container>
  11. }

Here’s the implementation of Container:

  1. use yew::{html, Children, Component, Html, Properties};
  2. #[derive(Properties, Clone)]
  3. pub struct Props {
  4. pub id: String,
  5. pub children: Children,
  6. }
  7. pub struct Container(Props);
  8. impl Component for Container {
  9. type Properties = Props;
  10. // ...
  11. fn view(&self) -> Html {
  12. html! {
  13. <div id=self.0.id.clone()>
  14. { self.0.children.clone() }
  15. </div>
  16. }
  17. }
  18. }

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.

  1. use yew::html;
  2. html! {
  3. <List>
  4. <ListItem value="a" />
  5. <ListItem value="b" />
  6. <ListItem value="c" />
  7. </List>
  8. }
  1. use yew::{html, ChildrenWithProps, Component, Html, Properties};
  2. #[derive(Properties, Clone)]
  3. pub struct Props {
  4. pub children: ChildrenWithProps<ListItem>,
  5. }
  6. pub struct List(Props);
  7. impl Component for List {
  8. type Properties = Props;
  9. // ...
  10. fn view(&self) -> Html {
  11. html!{{
  12. for self.0.children.iter().map(|mut item| {
  13. item.props.value = format!("item-{}", item.props.value);
  14. item
  15. })
  16. }}
  17. }
  18. }

Relevant examples