yew_utils/components/
table.rs

1use yew::prelude::*;
2
3use crate::vdom::{comp_with, tag};
4
5/// Table component around html tables.
6///
7/// Example:
8/// ```no_run
9/// use yew_utils::components::table::Table;
10/// use yew_utils::vdom::*;
11/// use yew::prelude::*;
12///
13/// # #[function_component(Example)]
14/// # fn example() -> Html {
15/// let columns = Children::new(
16///     ["col1", "col2"].map(|ea| text(ea).to_vnode()).to_vec(),
17/// );
18///
19/// let data = 0..5;
20/// let rows = data
21///     .into_iter()
22///     .map(|data| {
23///         tr().key(data.to_string())
24///             .append_all([
25///                 td().text(data.to_string()),
26///                 td().text(format!("{data} (col2)")),
27///             ])
28///             .to_vnode()
29///     })
30///     .collect::<Vec<_>>();
31///
32/// let table = Table::render(columns, yew::Children::new(rows));
33/// # todo!();
34/// # }
35/// ```
36
37pub struct Table;
38
39impl Table {
40    pub fn render(columns: Children, rows: Children) -> Html {
41        comp_with::<Table>(TableProps {
42            columns,
43            children: rows,
44        })
45        .to_vnode()
46    }
47}
48
49#[derive(PartialEq, Properties)]
50pub struct TableProps {
51    pub columns: Children,
52    pub children: Children,
53}
54
55impl Component for Table {
56    type Message = ();
57    type Properties = TableProps;
58
59    fn create(_ctx: &Context<Self>) -> Self {
60        Self
61    }
62
63    fn view(&self, ctx: &Context<Self>) -> Html {
64        let columns = &ctx.props().columns;
65        let children = &ctx.props().children;
66        tag("table")
67            .class("mui-table")
68            .append(
69                tag("thead").append(
70                    tag("tr").append_all(
71                        columns
72                            .iter()
73                            .enumerate()
74                            .map(|(i, node)| tag("th").append(node).key(i.to_string())),
75                    ),
76                ),
77            )
78            .append(tag("tbody").append_all(children.iter()))
79            .to_vnode()
80    }
81}