choose-matching
v1.0.0
Published
First element matching a boolean condition
Downloads
312
Readme
First element matching a boolean condition:
const Component = () => (
<section>
<header></header>
<nav>
{choose(
[test === "blue", <BlueButton />],
[test === "green", <GreenButton />],
[true, <Button />],
)}
</nav>
</section>
)
Why?
Because if
statement is a statement, but here we expect an expression.
Alternatives
Self-invoking function
<div>
{(() => {
switch (test) {
case "blue":
return <BlueButton />
case "green":
return <GreenButton />
default:
return <Button />
}
})()}
</div>
Pattern matching
Based on TC39 proposal or ts-pattern:
match (test) {
when ("blue"): <BlueButton />
when ("green"): <GreenButton />
default: <Button />
}
Modern way
Use languages in which if
and switch
are expressions, e.g. Civet.