<Switch> / <Match>
Edit this pageUseful for when there are more than 2 mutual exclusive conditions. It is a more flexible version of the if-else-if-else-if-else-... chain.
import { Switch, Match } from "solid-js"import type { MatchProps, JSX } from "solid-js"
function Switch(props: { fallback?: JSX.Element children: JSX.Element}): () => JSX.Element
type MatchProps<T> = { when: T | undefined | null | false children: JSX.Element | ((item: T) => JSX.Element)}function Match<T>(props: MatchProps<T>)
A super simple implementation of this component would be:
function Switch(props) { let children = props.children
if (!Array.isArray(children)) children = [children]
for (let i = 0; i < children.length; i++) { const child = children[i] if (child.props.when) return child }
return props.fallback}
For example, it can be used to perform basic routing:
<Switch fallback={<div>Not Found</div>}> <Match when={state.route === "home"}> <Home /> </Match> <Match when={state.route === "settings"}> <Settings /> </Match></Switch>
Match also supports function children to serve as keyed flow.
Switch props
fallback
Type: JSX.Element
The fallback element to render if no Match
component has a truthy when
prop.
Match props
when
Type: T | undefined | null | false
The condition to check.
If it is truthy, the children
will be rendered.