Switch

Picks one branch out of many. Renders the first case whose condition is true, and falls back to the default when none match.

API

Switch

proptypedefault
children?ReactNodethe cases and the default, as direct children

Switch.Case

proptypedefault
when?booleanfalsewhether this branch is taken
children?Renderablerendered when when is true

Switch.Default

proptypedefault
children?Renderablerendered when no case matches

Examples

Usage

tsx
<Switch>
  <Switch.Case when={status === "loading"}>
    <Spinner />
  </Switch.Case>
  <Switch.Case when={status === "error"}>{ErrorPanel}</Switch.Case>
  <Switch.Default>
    <Results rows={rows} />
  </Switch.Default>
</Switch>

Cases are read in order and the first match wins, so the branches can overlap without ambiguity: put the specific case above the general one and the general one becomes the implicit "otherwise". The Default may sit anywhere among them — it is only consulted once every case has failed — but reading order is easier to follow when it comes last.

Details

When to use it

Use it where Swap runs out of room: three or more branches, or conditions that read better as labels than as array positions.

How a branch is recognised

The Switch inspects its direct children and keeps those whose type is exactly Switch.Case or Switch.Default. Nothing else renders, so stray text or an unrelated element between the cases is dropped rather than displayed.

The consequence to remember: wrapping a case in a fragment, a div or a component of your own hides it from the Switch entirely. It is not a match that fails — the case simply stops existing, and the Switch falls through to the Default as if it had never been written.

tsx
<Switch>
  <>
    <Switch.Case when={isReady}>
      <Results rows={rows} />
    </Switch.Case>
  </>
</Switch>

If two Defaults are present the first one wins, for the same reason cases resolve top down.

What gets evaluated

Every case is an element, so JSX children of all branches are created before the Switch picks one — creating an element is cheap, but it is not free, and it is not deferral. When a branch must not be evaluated unless taken, pass it in component form: Renderable children accept a component, and the Switch calls it only for the branch it renders.