Control-flow components for matching discriminated union (tagged union) members and union literals.
npm install @solid-primitives/match
# or
yarn add @solid-primitives/match
# or
pnpm add @solid-primitives/matchControl-flow component for matching discriminated union (tagged union) members.
type MyUnion = {
type: "foo",
foo: "foo-value",
} | {
type: "bar",
bar: "bar-value",
}
const [value, setValue] = createSignal<MyUnion>({type: "foo", foo: "foo-value"})
<MatchTag on={value()} case={{
foo: v => <>{v().foo}</>,
bar: v => <>{v().bar}</>,
}} />The default tag key is "type", but it can be changed with the tag prop:
type MyUnion =
| {
kind: "foo";
foo: "foo-value";
}
| {
kind: "bar";
bar: "bar-value";
};
<MatchTag
on={value()}
tag="kind"
case={{
foo: v => <>{v().foo}</>,
bar: v => <>{v().bar}</>,
}}
/>;Use the partial prop to only handle some of the union members:
<MatchTag
partial
on={value()}
case={{
foo: v => <>{v().foo}</>,
// bar case is not handled
}}
/>Provide a fallback element when no match is found or the value is null/undefined:
<MatchTag
on={value()}
case={{
foo: v => <>{v().foo}</>,
bar: v => <>{v().bar}</>,
}}
fallback={<div>No match found</div>}
/>Control-flow component for matching union literals.
type MyUnion = "foo" | "bar";
const [value, setValue] = createSignal<MyUnion>("foo");
<MatchValue
on={value()}
case={{
foo: () => <p>foo</p>,
bar: () => <p>bar</p>,
}}
/>;Use the partial prop to only handle some of the union members:
<MatchValue
partial
on={value()}
case={{
foo: () => <p>foo</p>,
// bar case is not handled
}}
/>Provide a fallback element when no match is found or the value is null/undefined:
<MatchValue
on={value()}
case={{
foo: () => <p>foo</p>,
bar: () => <p>bar</p>,
}}
fallback={<div>No match found</div>}
/>Deployed example | Source code
See CHANGELOG.md