1.0.0 • Published 7 months ago

choose-matching v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

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.

1.0.0

7 months ago