Yew | 10, Conditional Rendering

Mike Code
Jul 18, 2024

--

We can use if expression to render some html conditionally.

use yew::{  function_component, html, Html,};

fn main() {
yew::Renderer::<App>::new().render();
}
#[function_component(App)]
fn app() -> Html {
let is_show = true;
html!(
<>
{
if is_show {
html!( <h1>{"hello"}</h1>)
} else {
html!(<h1>{"world"}</h1>)
}
}
</>
)
}

In app function component , we create a variable named is_show ,we give it a value true.

In html! macro , we create a if else expression , if is_show is true , then return <h1>{“hello”}</h1> in a html! macro , else return <h1>{“World”}</h1>in a html! macro.

So when we set is_show is true , it will render hello in web browser, if we change is_show to false , it will render world

--

--