How to dynamically generate elements list and pass it as typed children property? #2529
-
ListItem and List components// list_item.rs
#[derive(Properties, PartialEq, Clone)]
struct ListItemProps {
pub value: String,
}
#[function_component(ListItem)]
fn list_item(props: &ListItemProps) -> Html {
html! {
{props.value.clone()}
}
} // list.rs
#[derive(Clone, Properties, PartialEq)]
struct ListProps {
pub children: ChildrenWithProps<ListItem>,
}
#[function_component(List)]
fn list(props: &ListProps) -> Html {
html! {{
for props.children.iter().map(|mut item| {
let mut props = Rc::make_mut(&mut item.props);
props.value = format!("item-{}", props.value);
item
})
}}
} With static elements list all works good: html ! {
<List>
<ListItem value="0" />
<ListItem value="1" />
<ListItem value="2" />
</List>
} Trying to generate elements dinamically: html ! {
<List>
{for (0..3).map(|n: i32| html ! {
<ListItem value={n.to_string()} />
})}
</List>
} error:
|
Beta Was this translation helpful? Give feedback.
Answered by
WorldSEnder
Mar 19, 2022
Replies: 1 comment
-
The html ! {
<List>
- {for (0..3).map(|n: i32| html ! {
+ {for (0..3).map(|n: i32| html_nested ! {
<ListItem value={n.to_string()} />
})}
</List>
} The more technical reason this is necessary is that the |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
art-in
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
html_nested!
macro will come in handy and was made for this use case.The more technical reason this is necessary is that the
html!
macro erases the type of the component and always results in an expression of typeHtml
(an alias forVNode
you see in the error), whilehtml_nested!
preserves the top-most component type.