#[function_component]

#[function_component(_)] turns a normal Rust function into a function component. Functions with the attribute have to return Html and may take a single parameter for the type of props the component should accept. The parameter type needs to be a reference to a Properties type (ex. props: &MyProps). If the function doesn’t have any parameters the resulting component doesn’t accept any props.

The attribute doesn’t replace your original function with a component. You need to provide a name as an input to the attribute which will be the identifier of the component. Assuming you have a function called chat_container and you add the attribute #[function_component(ChatContainer)] you can use the component like this:

  1. use yew::{function_component, html, Html};
  2. #[function_component(ChatContainer)]
  3. pub fn chat_container() -> Html {
  4. html! {
  5. // chat container impl
  6. }
  7. }
  8. html! {
  9. <ChatContainer />
  10. };

Example

  • With props
  • Without props
  1. use yew::{function_component, html, Properties};
  2. #[derive(Properties, PartialEq)]
  3. pub struct RenderedAtProps {
  4. pub time: String,
  5. }
  6. #[function_component(RenderedAt)]
  7. pub fn rendered_at(props: &RenderedAtProps) -> Html {
  8. html! {
  9. <p>
  10. <b>{ "Rendered at: " }</b>
  11. { &props.time }
  12. </p>
  13. }
  14. }
  1. use yew::{function_component, html, use_state, Callback};
  2. #[function_component(App)]
  3. fn app() -> Html {
  4. let counter = use_state(|| 0);
  5. let onclick = {
  6. let counter = counter.clone();
  7. Callback::from(move |_| counter.set(*counter + 1))
  8. };
  9. html! {
  10. <div>
  11. <button {onclick}>{ "Increment value" }</button>
  12. <p>
  13. <b>{ "Current value: " }</b>
  14. { *counter }
  15. </p>
  16. </div>
  17. }
  18. }

Generic function components

The #[function_component(_)] attribute also works with generic functions for creating generic components.

my_generic_component.rs

  1. use std::fmt::Display;
  2. use yew::{function_component, html, Properties};
  3. #[derive(Properties, PartialEq)]
  4. pub struct Props<T>
  5. where
  6. T: PartialEq,
  7. {
  8. data: T,
  9. }
  10. #[function_component(MyGenericComponent)]
  11. pub fn my_generic_component<T>(props: &Props<T>) -> Html
  12. where
  13. T: PartialEq + Display,
  14. {
  15. html! {
  16. <p>
  17. { &props.data }
  18. </p>
  19. }
  20. }
  21. // used like this
  22. html! {
  23. <MyGenericComponent<i32> data=123 />
  24. };
  25. // or
  26. html! {
  27. <MyGenericComponent<String> data={"foo".to_string()} />
  28. };