Course contentsShow
← React
Lesson 130 of 2,3964. Conditional Rendering in JSXFree lesson

Switch Statements in IIFEs

Handle multiple discrete branches cleanly with switch statements inside IIFEs when the logic belongs in the render.

Switch Statements in IIFEs

You'll learn how to handle multiple discrete branches cleanly inside JSX when ternaries become too messy.


Sometimes you have more than two or three possible outcomes—imagine rendering different UI based on a user's account status: "guest", "member", "premium", or "admin". Nested ternaries quickly become unreadable. Since switch statements are statements (not expressions), they can't go directly in JSX. But you've already learned about IIFEs—immediately invoked function expressions—which let you run statement-based logic and return a value inline.

By wrapping a switch inside an IIFE, you get clean, readable branching right where you need it in your JSX.

How It Works

function AccountBadge({ status }) {
  return (
    <div>
      {(() => {
        switch (status) {
          case 'guest':
            return <span>🔓 Guest</span>;
          case 'member':
            return <span>👤 Member</span>;
          case 'premium':
            return <span>⭐ Premium</span>;
          case 'admin':
            return <span>🛡️ Admin</span>;
          default:
            return <span>❓ Unknown</span>;
        }
      })()}
    </div>
  );
}

The (() => { ... })() creates and immediately invokes an arrow function. Inside, the switch evaluates status and returns the appropriate JSX. React renders that returned value.

When to Use This

  • Multiple discrete options (4+ cases)
  • Logic belongs in the render, not extracted before
  • Each case is simple enough to inline

If the logic gets complex, prefer extracting to a variable with if/else before the return.

Key Takeaway: Use switch statements inside IIFEs when you have many discrete branches and want to keep the branching logic inline in JSX—cleaner than deeply nested ternaries.