Expand description
Utilities for conditional rendering
The view!
macro produces unique transient types, so you might run into compile errors when branching:
ⓘ
#[component]
fn Conditional(illuminatus: bool) -> impl View {
if illuminatus {
view! { <p>"It was the year when they finally immanentized the Eschaton."</p> }
} else {
view! { <blockquote>"It was love at first sight."</blockquote> }
}
}
Here Rust will inform you that:
/ if illuminatus {
| view! { <p>"It was the year when they finally immanentized the Eschaton."</p> }
| ------------------------------------------------------------------------------- expected because of this
| } else {
| view! { <blockquote>"It was love at first sight."</blockquote> }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Conditional::render::Transient`, found a different struct `Conditional::render::Transient`
| }
|_____- `if` and `else` have incompatible types
While both types are named Transient
, they are in fact different types defined inline by the macro.
In most cases all you have to do is annotate such component with #[component(auto_branch)]
:
#[component(auto_branch)]
fn Conditional(illuminatus: bool) -> impl View {
if illuminatus {
view! { <p>"It was the year when they finally immanentized the Eschaton."</p> }
} else {
view! { <blockquote>"It was love at first sight."</blockquote> }
}
}
This flag is not enabled by default, yet, as there might be situations auto_branch
doesn’t handle correctly.
Manual branching
An always safe if more laborious way is to manually use one of the BranchN
enums from this module:
use kobold::branching::Branch2;
#[component]
fn Conditional(illuminatus: bool) -> impl View {
if illuminatus {
Branch2::A(view! {
<p>"It was the year when they finally immanentized the Eschaton."</p>
})
} else {
Branch2::B(view! {
<blockquote>"It was love at first sight."</blockquote>
})
}
}
This is in fact all that the auto_branch
flag does for you automatically.
For simple optional renders you can always use the standard library Option
:
#[component]
fn Conditional(illuminatus: bool) -> impl View {
if illuminatus {
Some(view! {
<p>"It was the year when they finally immanentized the Eschaton."</p>
})
} else {
None
}
}