How to Use Switch-Case Statement in JSX with React.js or Next.js


We’ll often want to conditionally render different components in JSX.

A switch statement seems like it would work well, but how can we use, or at least simulate, a switch-case statement in JSX?

Switch statement in a regular function

We can extract the switch statement logic from the JSX and place it into a function.

const Component = ({ param }) => {
  const = simulateSwitch(param) => {
    switch(param) {
      case 'foo':
        return <Foo />;
      case 'bar':
        return <Bar />;
      default:
        return <Baz />;
    }
  }
  return (
    <div>
      {simulateSwitch(param)}
    </div>
  );
}

Switch statement in a separate component

We can create an entirely new Switch component to cleanly simulate switch statements.

Let’s create this component to take in a test variable that will eventually be the expression we evaluate against.

Every child of this component will be a case in our switch statement. The value of that case will be stored in the props of that child, namely the value property. Let’s make a Case component as well.

Lastly, we can add a defaultComponent that will render when no case value matches the test property.

const Switch = ({ test, defaultComponent, children }) => {
  return children.find(child => {
    return child.props.value === test;
  }) || defaultComponent;
}
const Case = ({ value, children }) => {
  return children; 
}

We can then use our new Switch and Case components.

const Component = ({ param }) => {
  return (
    <Switch test={param} defaultComponent={<Baz />}>
      <Case value="foo"><Foo /></Case>
      <Case value="bar"><Bar /></Case>
    </Switch>
  )
}

Let’s compare this to a normal switch statement.

switch(param) {
  case 'foo':
    return <Foo />;
  case 'bar':
    return <Bar />;
  default:
    return <Baz />;
}

Switch statement using inline JSX

We can also simulate a switch statement using a simple JavaScript object sitting inside our JSX.

const Component = ({ param }) => {
  return (
    <div>
      {
        {
          'foo': <Foo />,
          'bar': <Bar />
        }[param] || <Baz />
      }
    </div>
  );
}

We’re placing all switch cases into a POJO (Plain Old JavaScript Object), and simply grabbing the component based on the key.

A default can be rendered using the || operator if the param key doesn’t exist at the time of render.