MatchOption
Provides a declarative switch-case pattern. It compares the [Match] component's value against the is prop of its [Option] children. The first matching [Option] is rendered; otherwise, the fallback is displayed.
Demo
INFO
The component has an array of numbers and a variable state number used like index of array. Every 2 seconds index changes value. It uses MatchOption component to render different p element with a text indicating the value of array with the current index.
Loading demo…
Show source code
tsx
import { useEffect, useRef, useState } from "react";
import { MatchOption } from "../../../";
export default function SM() {
const valuesCounter = useRef([1, 2, 3]);
const [indexCounter, setIndexCounter] = useState(0);
useEffect(() => {
const id = setInterval(() => setIndexCounter(i => i%4+1 === 4 ? 0 : i%4+1), 2000);
return () => clearInterval(id);
}, []);
return (<div style={{textAlign: "left", display: "flex", flexDirection: "column", alignItems: "center"}}>
<p style={{width: 230}}>Counter values: {JSON.stringify(valuesCounter.current, null, 2)}</p>
<p style={{width: 230}}>Counter index: {indexCounter}</p>
<MatchOption.Match value={indexCounter} fallback={<p style={{color: "darkorange", width: 230}}>Counter value unsetted.</p>}>
<MatchOption.Option is={0}>
<p style={{color: "darkturquoise", width: 230, fontWeight: 800}}>Counter value is 1.</p>
</MatchOption.Option>
<MatchOption.Option is={(value) => value === 1}>
<p style={{color: "darkkhaki", width: 230, fontWeight: 800}}>Counter value is 2.</p>
</MatchOption.Option>
<MatchOption.Option is={2}>
<p style={{color: "darkcyan", width: 230, fontWeight: 800}}>Counter value is 3.</p>
</MatchOption.Option>
</MatchOption.Match>
</div>);
}Types
MatchProps
@templateT - The type of thevalueto be compared.
Props accepted by the MatchOption component.
| Property | Type | Required | Description |
|---|---|---|---|
value | T | ✓ | The central value to compare against the is prop of each <MatchOption.Option> child. The first <MatchOption.Option> whose is value or function strictly matches (===) this value will be rendered. |
children | \| ReactElement<OptionProps<T>> \| ReactElement<OptionProps<T>>[] \| undefined | One or more {@link Option} elements to evaluate in order. The first Option whose is prop is truthy is rendered; all others are ignored. | |
fallback | ReactNode | Optional content rendered when no <MatchOption.Option> matches the provided value. Accepts any valid React node. |
OptionProps
@templateT - The type of theisvalue, should match thevaluetype of the parent <MatchOption.Match>.
Props accepted by the MatchOption component.
| Property | Type | Required | Description |
|---|---|---|---|
is | T \| ((value:T) => boolean) | ✓ | The value used to determine if this option should be rendered. If is === value (from the parent [Match]), the children are displayed. |
