This guide explains how to conditionally render a component based on some condition.
The logical &&
displays the right hand side component when the left condition is true, otherwise do not render anything.
const TestConditionalAndAnd = () => {
const showState = bau.state(true);
return section(
h1("Logical &&"),
button({ onclick: () => (showState.val = !showState.val) }, "Toogle"),
p(() => showState.val && "ON")
);
};
The ternary operator displays one component or another:
const TestConditionalTernary = () => {
const showState = bau.state(true);
return section(
h1("Conditonal with &&"),
button({ onclick: () => (showState.val = !showState.val) }, "Toogle"),
() => (showState.val ? p("ON") : p("OFF"))
);
};
The if and else Javascript keywords can be used to conditional render components.
const TestConditionalIfElse = () => {
const showState = bau.state(true);
return section(
h1("Conditonal with if else"),
button({ onclick: () => (showState.val = !showState.val) }, "Toogle"),
() => {
if (showState.val) {
return p("ON");
} else {
return p("OFF");
}
}
);
};
In this conditional, we'll define an object that map a key name to a component.
const UserView = () => div("User View");
const AdminView = () => div("Admin View");
const viewMap: any = {
user: UserView,
admin: AdminView,
};
const TestConditionalMap = () => {
const showViewState = bau.state("user");
return section(
h1("Conditional with map"),
button({ onclick: () => (showViewState.val = "admin") }, "Admin"),
button({ onclick: () => (showViewState.val = "user") }, "User"),
() => viewMap[showViewState.val]()
);
};
This conditional removes the element from the layout by setting the CSS style property display to none.
const TestConditionalDisplayNone = () => {
const hideState = bau.state(false);
return section(
h1('Conditional with style: "display: none"'),
button({ onclick: () => (hideState.val = !hideState.val) }, "Toogle"),
p({ style: () => hideState.val && "display:none" }, "ON")
);
};
style: "visibility:hidden"
This conditional hides the element by setting the CSS style property visibility to hidden. In this case the element stays in the layout but is hidden.
const TestConditionalVisitbilityHidden = () => {
const hideState = bau.state(false);
return article(
h1('Conditional with style: "visibility:hidden"'),
button({ onclick: () => (hideState.val = !hideState.val) }, "Toogle"),
p({ style: () => hideState.val && "visibility:hidden" }, "ON")
);
};