@@ -71,3 +71,98 @@ html! {
7171
7272 </TabItem >
7373</Tabs >
74+
75+ ## Using typed children
76+
77+ Assuming you have a component which uses ` ChildrenRenderer<T> ` or ` ChildrenWithProps<T> ` , it is currently not possible
78+ to use the ` if ` syntax. However, as it is possible to use an ` Iterator<T> ` and ` Option<T> ` implements the iterator trait
79+ in Rust, this can be transformed into using ` for ` instead.
80+
81+ Assuming you have the following component structure, ` Parent ` only accepting children of the type ` Child ` :
82+
83+ ``` rust
84+ use yew :: prelude :: * ;
85+ use yew :: html :: ChildrenRenderer ;
86+
87+ #[function_component(Child )]
88+ fn child () -> Html {
89+ html! {}
90+ }
91+
92+ #[derive(PartialEq , Properties )]
93+ struct ParentProperties {
94+ pub children : ChildrenRenderer <Child >,
95+ }
96+
97+ #[function_component(Parent )]
98+ fn parent () -> Html {
99+ html! {}
100+ }
101+ ```
102+
103+ Then it is possible to compose the children using ` for ` , translating the ` bool ` condition into an ` Option ` using
104+ ` Option::then ` :
105+
106+ <Tabs >
107+ <TabItem value = " typed-children-valid" label = " Using for" >
108+
109+ ``` rust
110+ use yew :: prelude :: * ;
111+ use yew :: html :: ChildrenRenderer ;
112+
113+ // component definition
114+
115+ #[function_component(Child )]
116+ fn child () -> Html { html! {} }
117+
118+ #[derive(PartialEq , Properties )]
119+ struct ParentProperties {
120+ pub children : ChildrenRenderer <Child >,
121+ }
122+
123+ #[function_component(Parent )]
124+ fn parent () -> Html { html! {} }
125+
126+ // Making use of the `for` construct
127+
128+ #[function_component(Example )]
129+ fn example () -> Html {
130+ let condition = true ; // or false
131+
132+ html! {
133+ <Parent >
134+ <Child / > // first child
135+ <Child / > // second child
136+ { for condition . then (|| html_nested! (
137+ <Child / > // optional third child
138+ )) }
139+ </ Parent >
140+ }
141+ }
142+ ```
143+
144+ </TabItem >
145+
146+ <TabItem value = " typed-children-invalid" label = " Invalid" >
147+
148+ What does not work is to use the ` if ` keyword directly, as it turns the component into an untyped children, which
149+ cannot be assigned to the typed children types.
150+
151+ ``` rust, compile_fail
152+ use yew::prelude::*;
153+
154+ let condition = true; // or false
155+
156+ html! {
157+ <Parent>
158+ <Child />
159+ <Child />
160+ if condition {
161+ <Child /> // optional third child
162+ }
163+ </Parent>
164+ }
165+ ```
166+
167+ </TabItem >
168+ </Tabs >
0 commit comments