Inspecting and manipulating Children can often result in surprising and hard-to-explain behaviours in your application. This can lead to edge cases and often does not yield expected result.
You should consider other approaches if you are trying to manipulate Children.
Yew supports using Html as the type of the children prop. You should use Html as children if you do not need Children or ChildrenRenderer. It doesn't have the drawbacks of Children and has a lower performance overhead.
Most of the time, when allowing a component to have children, you don't care what type of children the component has. In such cases, the below example will suffice.
Of course, sometimes you might need to restrict the children to a few different components. In these cases, you have to get a little more hands-on with Yew.
The derive_more crate is used here for better ergonomics. If you don't want to use it, you can manually implement From for each variant.
useyew::{
html,html::ChildrenRenderer,virtual_dom::VChild, Component,
Context, Html, Properties,};pubstructPrimary;implComponent forPrimary{typeMessage=();typeProperties=();fncreate(_ctx:&Context<Self>)->Self{Self}fnview(&self, _ctx:&Context<Self>)-> Html{html!{{"Primary"}}}}pubstructSecondary;implComponent forSecondary{typeMessage=();typeProperties=();fncreate(_ctx:&Context<Self>)->Self{Self}fnview(&self, _ctx:&Context<Self>)-> Html{html!{{"Secondary"}}}}#[derive(Clone, derive_more::From, PartialEq)]pubenumItem{
Primary(VChild<Primary>),
Secondary(VChild<Secondary>),}// Now, we implement `Into<Html>` so that yew knows how to render `Item`.
#[allow(clippy::from_over_into)]implInto<Html>forItem{fninto(self)-> Html{matchself{Self::Primary(child)=> child.into(),Self::Secondary(child)=> child.into(),}}}#[derive(Properties, PartialEq)]pubstructListProps{
#[prop_or_default]
pubchildren:ChildrenRenderer<Item>,
}pubstructList;implComponent forList{typeMessage=();typeProperties= ListProps;fncreate(_ctx:&Context<Self>)->Self{Self}fnview(&self, ctx:&Context<Self>)-> Html{html!{<div class="list">{for ctx.props().children.iter()}</div>}}}
For a real-world example of this pattern, check out the yew-router source code. For a more advanced example, check out the nested-list example in the main yew repository.