docs / Runtime

Switch and Match

First-match branching with components instead of else-if chains.

Switch picks the FIRST Match whose condition is truthy, and renders fallback when none match. It is the component form of an else-if chain: the cases read as a table, the order is explicit, and the whole thing is one value you can pass to a helper.

app/status/page.vsk
									
										component Status(props: { state: string }) {
  <Switch fallback={<p class="unknown">Unknown</p>}>
    <Match when={props.state === 'loading'}><p>Loading…</p></Match>
    <Match when={props.state === 'error'}><p class="err">Something broke.</p></Match>
    <Match when={props.state === 'ready'}><p>All done.</p></Match>
  </Switch>
}
									
								

Order is the whole point: Switch takes the first match, so put the most specific cases first.

Driven by a cell

when is a normal tracked expression, so switching cases re-renders the branch that changed — and only that branch.

app/status/page.vsk
									
										component Status() {
  const &[state] = track('loading')

  <Switch fallback={<p>Unknown</p>}>
    <Match when={state === 'loading'}><p>Loading…</p></Match>
    <Match when={state === 'error'}><p>Something broke.</p></Match>
    <Match when={state === 'ready'}><p>Done.</p></Match>
  </Switch>
  <button onClick={() => state = 'ready'}>finish</button>
}
									
								

No fallback

Without a fallback, a Switch where nothing matches renders nothing — the right default for a switch that is meant to be exhaustive.