Switch and Match
Handling more than two branches of conditional UI cleanly, without a chain of nested <Show> components.
2 menit membaca
<Show> handles a single true/false condition well, but once you have three, four, or more mutually exclusive branches, nesting <Show> components gets unwieldy fast. Solid's answer is <Switch> and <Match> — the JSX equivalent of a switch statement.
The problem: nested Show for multiple states
<Show when={status() === "loading"} fallback={
<Show when={status() === "error"} fallback={
<Show when={status() === "success"}>
<p>Loaded successfully!</p>
</Show>
}>
<p>Something went wrong.</p>
</Show>
}>
<p>Loading...</p>
</Show>This works, but it's hard to read, hard to extend, and the nesting depth grows with every new state you need to handle.
Switch and Match flatten it
import { Switch, Match } from "solid-js";
function Status(props) {
return (
<Switch fallback={<p>Unknown status</p>}>
<Match when={props.status === "loading"}>
<p>Loading...</p>
</Match>
<Match when={props.status === "error"}>
<p>Something went wrong.</p>
</Match>
<Match when={props.status === "success"}>
<p>Loaded successfully!</p>
</Match>
</Switch>
);
}<Switch> checks its <Match> children in order and renders the first one whose when condition is truthy — the rest are skipped entirely, similar to a JavaScript switch's fall-through-free branches. If none match, <Switch>'s own fallback prop renders instead. This is a direct structural parallel to <Show>'s when/fallback, just extended to more than two branches.
Match also exposes the resolved value
Like <Show>, a <Match>'s children can be a function that receives the resolved (truthy) value of when — handy when you're branching on something more than a plain string comparison:
<Switch>
<Match when={currentUser()}>
{(user) => <p>Signed in as {user().email}</p>}
</Match>
<Match when={!currentUser()}>
<p>Not signed in</p>
</Match>
</Switch>Why not just a JavaScript switch statement?
You could write a plain switch inside a function and return different JSX per case — and it would run correctly. But like the plain ternary from the <Show> lesson, a raw JavaScript switch gives Solid's compiler no stable structure to optimize: it can't tell which branch is "the same as last time" versus a fresh subtree to construct. <Switch>/<Match>, being real components in the JSX tree, let Solid track and reuse the currently active branch efficiently as state changes, the same way <Show> does for a single condition.
Rule of thumb
- One condition, two outcomes →
<Show>. - Three or more mutually exclusive outcomes →
<Switch>/<Match>. - Rendering a collection →
<For>(previous lesson), never<Switch>.
Together, <Show>, <For>, and <Switch>/<Match> replace nearly every case where you'd normally reach for a ternary, &&, .map, or a switch statement inside JSX — and in each case, the reason is the same: they give Solid's compiler a stable shape to optimize around, instead of an opaque JavaScript expression.