
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