DEV Community

Cover image for Switch Statements in JSX
David Woodward
David Woodward

Posted on

2 2

Switch Statements in JSX

JSX allows us to describe our UI using javascript expressions. This has interesting implications for control flow, because control flow statements in javascript (if, for, switch, etc) do not return values (they are imperative). This means that while we can use control flow statements to return top-level blocks of JSX,

if (isLoading) {
  return <span>loading...</span>
} else {
  return (
    <section>
      <h1>My content</h1>
      {content}
    </section>
  )
}
Enter fullscreen mode Exit fullscreen mode

we cannot use them inline.

return (
  <section>
    <h1>My content</h1>
    {/* this is a syntax error ... */}
    {if (isLoading) {
      return <span>loading</span>
    } else {
      return content
    }}
  </section>
)
Enter fullscreen mode Exit fullscreen mode

However, since JSX allows for embedded Javascript expressions, rather than statements, we can mimic the functionality of if, else and switch using the ternary operator!

// a simple if-else
return (
  <section>
    <h1>My content</h1>
    {isLoading ? (
      <span>loading</span>
    ) : (
      content
    )}
  </section>
)

// a switch (nested ternary)
return (
  <section>
    <h1>My content</h1>
    {isLoading ? (
      <span>loading</span>
    ) : hasErrors ? (
      <span>something went wrong</span>
    ) : (
      content // this is the last "else" case
    )}
  </section>)
Enter fullscreen mode Exit fullscreen mode

Scrupulous style guide adherents may claim that nested ternaries are confusing and error prone, but functionally it's not different then an if-else-if chain. If you and your linter can get used to it, I think it's a cleaner way to represent switch logic in JSX!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
danwood profile image
Dan Wood

That sure looks ugly, confusing and error prone to me.

But that's my personal preference.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay