Generic Components

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

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