Skip to main content
A wizard in a blue robe and hat, standing amidst a mystical forest with shimmering lights. He presents a choice between 'if-else' in one hand and 'switch(true)' in the other.

switch(true): The Stylish Way to Simplify Complex Conditionals in React

Hello awesome people! 🌈

So, you’re building a React app, carving components like a Michelangelo of the modern web. Your if-else ladders and switch-case blocks stand as a testament to conditional rendering. But have you ever thought, “Hmmm, there must be a more elegant way to do this”?

Today, I’m going to introduce you to a quirky little trick: switch(true). It’s like the Swiss Army knife of control flow, allowing you to untangle nested if-else chains and write more legible code. I’ll be honest, even though I’ve been writing JavaScript code for over a decade now, I didn’t know you could use switch(true) until a month ago. But once I discovered it, I was hooked. It’s become my go-to approach for handling complex conditionals in React, and I’m excited to share it with you.

The Usual Suspects

Before we talk about switch(true), let’s look at a typical control flow scenario. You’re probably familiar with the following patterns:

The If-Else Ladder

const Notification = ({ type }: { type: string }) => {
  if (type === "success") {
    return <SuccessNotification />;
  } else if (type === "error") {
    return <ErrorNotification />;
  } else if (type === "warning") {
    return <WarningNotification />;
  } else {
    return <DefaultNotification />;
  }
};

The Classic Switch-Case

const Notification = ({ type }: { type: string }) => {
  switch (type) {
    case "success":
      return <SuccessNotification />;
    case "error":
      return <ErrorNotification />;
    case "warning":
      return <WarningNotification />;
    default:
      return <DefaultNotification />;
  }
};

Both are time-tested but have their limitations. If-else ladders can be harder to read as complexity grows. On the other hand, while switch-case is usually concise, some developers find it less flexible for handling complex conditions.

Enter switch(true)

If you’re looking for a middle ground, switch(true) could be your secret weapon. It’s an oddball, because it flips the switch paradigm on its head. Rather than matching a value against different cases, it evaluates expressions within the case statements.

In Action

const Notification = ({ type }: { type: string }) => {
  switch (true) {
    case type === "success":
      return <SuccessNotification />;
    case type === "error":
      return <ErrorNotification />;
    case type === "warning":
      return <WarningNotification />;
    default:
      return <DefaultNotification />;
  }
};

Boom! 🎉 We’ve cut the gordian knot. The switch(true) style of writing conditionals can lead to much cleaner, more expressive code.

Taking It a Step Further

Alright, folks. Let’s not stop at just looking good; let’s actually be good. How can we maximize the utility of this trick?

With Object Properties

Imagine you have a component that needs to render different elements based on status and isAdmin:

const UserInfo = ({
  status,
  isAdmin,
}: {
  status: string;
  isAdmin: boolean;
}) => {
  switch (true) {
    case status === "active" && isAdmin:
      return <AdminActiveUser />;
    case status === "inactive" && isAdmin:
      return <AdminInactiveUser />;
    case status === "active":
      return <ActiveUser />;
    default:
      return <InactiveUser />;
  }
};

By using switch(true), you’re not just limited to checking one variable. You can form complex expressions that’ll make your code as clean as a freshly laundered lab coat.

With Functions and Ternary Operators

You can get even more expressive by embedding functions or ternary operators in your switch(true):

const isMajorVersionUpdate = (currentVersion: string, newVersion: string) => {
  return parseInt(newVersion, 10) > parseInt(currentVersion, 10);
};

const UpdateNotification = ({
  currentVersion,
  newVersion,
}: {
  currentVersion: string;
  newVersion: string;
}) => {
  switch (true) {
    case isMajorVersionUpdate(currentVersion, newVersion):
      return <MajorVersionNotification />;
    case newVersion !== currentVersion:
      return <MinorVersionNotification />;
    default:
      return <NoUpdateNotification />;
  }
};

This keeps your switch(true) block clean and offloads the logic to named functions, which can be unit-tested separately.

Wrapping Up

Hopefully, you’re as jazzed as I am about this unusual but incredibly powerful trick. switch(true) offers an elegant way to handle complex conditionals, and once you start using it, you may find it difficult to go back to those if-else ladders and vanilla switch-case blocks.

Now, like any tool in your developer toolbox, switch(true) isn’t going to be everyone’s cup of tea ☕. And that’s okay! Some of you might fall head over heels for this approach, admiring its ability to make control flow more expressive without sacrificing readability. Others might cringe a little, finding it unconventional and counterintuitive compared to the tried-and-true if-else or switch-case patterns. And hey, we can have differing opinions and still be friends, right? The key takeaway is to recognize it as another option on your palette of best practices. Whether it becomes your go-to approach or just a trick you pull out on special occasions, being aware of switch(true) and its benefits can only make you a more versatile React developer. 🌟

Go ahead, give it a spin in your next React project and let me know how it turns out. Until next time, keep coding! 🚀

Stay in touch

Don't miss out on new posts or project updates. Hit me up on X (Twitter) for updates, queries, or some good ol' tech talk.

Follow @zkMake
Zubin Khavarian's Profile Photo Written by Zubin Khavarian