Skip to content

Commit 23debb4

Browse files
committed
docs: explain a workaround for if with typed children
1 parent 1d88934 commit 23debb4

1 file changed

Lines changed: 93 additions & 0 deletions

File tree

website/docs/concepts/html/conditional-rendering.mdx

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,96 @@ 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+
86+
#[function_component(Child)]
87+
fn child() -> Html {
88+
html! {}
89+
}
90+
91+
#[derive(PartialEq, Properties)]
92+
struct ParentProperties {
93+
pub children: ChildrenWithProps<Child>,
94+
}
95+
96+
#[function_component(Parent)]
97+
fn parent(props: &ParentProperties) -> Html {
98+
html! {}
99+
}
100+
```
101+
102+
Then it is possible to compose the children using `for`, translating the `bool` condition into an `Option` using
103+
`Option::then`:
104+
105+
<Tabs>
106+
<TabItem value="typed-children-valid" label="Using for">
107+
108+
```rust
109+
use yew::prelude::*;
110+
111+
// component definition
112+
113+
#[function_component(Child)]
114+
fn child() -> Html { html! {} }
115+
116+
#[derive(PartialEq, Properties)]
117+
struct ParentProperties {
118+
pub children: ChildrenWithProps<Child>,
119+
}
120+
121+
#[function_component(Parent)]
122+
fn parent(props: &ParentProperties) -> Html { html! {} }
123+
124+
// Making use of the `for` construct
125+
126+
#[function_component(Example)]
127+
fn example() -> Html {
128+
let condition = true; // or false
129+
130+
html! {
131+
<Parent>
132+
<Child /> // first child
133+
<Child /> // second child
134+
{ for condition.then(|| html_nested!(
135+
<Child /> // optional third child
136+
)) }
137+
</Parent>
138+
}
139+
}
140+
```
141+
142+
</TabItem>
143+
144+
<TabItem value="typed-children-invalid" label="Invalid">
145+
146+
What does not work is to use the `if` keyword directly, as it turns the component into an untyped children, which
147+
cannot be assigned to the typed children types.
148+
149+
```rust, compile_fail
150+
use yew::prelude::*;
151+
152+
let condition = true; // or false
153+
154+
html! {
155+
<Parent>
156+
<Child />
157+
<Child />
158+
if condition {
159+
<Child /> // optional third child
160+
}
161+
</Parent>
162+
}
163+
```
164+
165+
</TabItem>
166+
</Tabs>

0 commit comments

Comments
 (0)