Components
Basic
Components can be used in the html! macro:
1. use yew::prelude::*;
3. #[function_component]
4. fn MyComponent() -> Html {
5. html! {
6. { "This component has no properties!" }
7. }
8. }
10. #[derive(Clone, PartialEq, Properties)]
11. struct Props {
12. user_first_name: String,
13. user_last_name: String,
14. }
16. #[function_component]
17. fn MyComponentWithProps(props: &Props) -> Html {
18. let Props { user_first_name, user_last_name } = props;
19. html! {
20. <>{"user_first_name: "}{user_first_name}{" and user_last_name: "}{user_last_name}</>
21. }
22. }
24. let props = Props {
25. user_first_name: "Bob".to_owned(),
26. user_last_name: "Smith".to_owned(),
27. };
29. html!{
30. <>
31. // No properties
32. <MyComponent />
34. // With Properties
35. <MyComponentWithProps user_first_name="Sam" user_last_name="Idle" />
37. // With the whole set of props provided at once
38. <MyComponentWithProps ..props.clone() />
40. // With Properties from a variable and specific values overridden
41. <MyComponentWithProps user_last_name="Elm" ..props />
42. </>
43. };
Nested
Components can accept child components/elements if they have a children field in their Properties
parent.rs
1. use yew::prelude::*;
3. #[derive(PartialEq, Properties)]
4. struct Props {
5. id: String,
6. children: Html,
7. }
9. #[function_component]
10. fn Container(props: &Props) -> Html {
11. html! {
12. <div id={props.id.clone()}>
13. { props.children.clone() }
14. </div>
15. }
16. }
18. html! {
19. <Container id="container">
20. <h4>{ "Hi" }</h4>
21. <div>{ "Hello" }</div>
22. </Container>
23. };
The html! macro allows you to pass a base expression with the ..props syntax instead of specifying each property individually, similar to Rust’s Functional Update Syntax. This base expression must occur after any individual props are passed. When passing a base props expression with a children field, the children passed in the html! macro overwrite the ones already present in the props.
1. use yew::prelude::*;
3. #[derive(PartialEq, Properties)]
4. struct Props {
5. id: String,
6. children: Html,
7. }
9. #[function_component]
10. fn Container(props: &Props) -> Html {
11. html! {
12. <div id={props.id.clone()}>
13. { props.children.clone() }
14. </div>
15. }
16. }
18. let props = yew::props!(Props {
19. id: "container-2",
20. children: Html::default(),
21. });
23. html! {
24. <Container ..props>
25. // props.children will be overwritten with this
26. <span>{ "I am a child, as you can see" }</span>
27. </Container>
28. };
