2025-07-21 10:06:41 +09:00

45 lines
785 B
Plaintext

---
title: 'Generic Components'
description: 'The #[component] attribute'
---
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
The `#[component]` attribute also works with generic functions for creating generic components.
```rust
use std::fmt::Display;
use yew::{component, html, Properties, Html};
#[derive(Properties, PartialEq)]
pub struct Props<T>
where
T: PartialEq,
{
data: T,
}
#[component]
pub fn MyGenericComponent<T>(props: &Props<T>) -> Html
where
T: PartialEq + Clone + Into<Html>,
{
html! {
<p>
{ props.data.clone().into() }
</p>
}
}
// then can be used like this
html! {
<MyGenericComponent<i32> data=123 />
};
// or
html! {
<MyGenericComponent<String> data={"foo".to_string()} />
};
```