Components

<Switch> / <Match>

Edit this page

<Switch> renders the first child <Match> whose when prop is truthy. <Match> can render JSX directly or accept a function child.


Import

import { Match, Switch } from "solid-js";

Type

type Accessor<T> = () => T;
function Switch(props: {
fallback?: JSX.Element;
children: JSX.Element;
}): JSX.Element;
function Match<T>(props: {
when: T | undefined | null | false;
keyed?: false;
children: JSX.Element | ((item: Accessor<NonNullable<T>>) => JSX.Element);
}): JSX.Element;
function Match<T>(props: {
when: T | undefined | null | false;
keyed: true;
children: JSX.Element | ((item: NonNullable<T>) => JSX.Element);
}): JSX.Element;

<Switch> props

fallback

  • Type: JSX.Element

Content rendered when no child <Match> has a truthy when value.

children

  • Type: JSX.Element

Child <Match> elements.


<Match> props

when

  • Type: T | undefined | null | false

Condition value for the branch.

keyed

  • Type: boolean

Controls whether function children receive the current value directly instead of an accessor.

children

  • Type: JSX.Element | ((item: Accessor<NonNullable<T>>) => JSX.Element) | ((item: NonNullable<T>) => JSX.Element)

Content rendered when the branch matches.


Return value

  • Type: JSX.Element

Returns the selected branch or the fallback content.


Behavior

  • <Switch> evaluates its child <Match> elements in order and renders only the first truthy branch.
  • If no branch matches, <Switch> renders fallback.
  • Function children in <Match> are wrapped in untrack.
  • With keyed={false}, function children in <Match> receive an accessor that can only be read while that branch remains selected. Replacing one truthy value with another truthy value does not recreate the child block.
  • With keyed={true}, function children receive the current value directly, and changing the when value recreates the child block even when it remains truthy.

Examples

Basic usage

import { createSignal } from "solid-js";
const [status, setStatus] = createSignal<"loading" | "success" | "error">(
"loading"
);
<>
<button onClick={() => setStatus("loading")}>Loading</button>
<button onClick={() => setStatus("success")}>Success</button>
<button onClick={() => setStatus("error")}>Error</button>
<Switch fallback={<p>Unknown status</p>}>
<Match when={status() === "loading"}>
<p>Loading...</p>
</Match>
<Match when={status() === "success"}>
<p>Saved</p>
</Match>
<Match when={status() === "error"}>
<p>Failed</p>
</Match>
</Switch>
</>;

Report an issue with this page