-
Notifications
You must be signed in to change notification settings - Fork 5
Switch
Static flow component similar to SolidJS <Switch>
, can also act similar to a JavaScript switch statement using name
prop
Note: Designed to be used with the
<When>
component, this it is not required when usingname
prop
This component is useful when you want to do advanced conditional rendering
There are two ways of using this switch component
---
import { Switch, When } from 'astro-headless-ui';
---
// Using with `<When>`
<Switch>
<h1>Default is True</h1>
<When slot="1">
<h1>One</h1>
</When>
<When slot="2" is={true}>
<h1>Two</h1>
</When>
<When slot="3">
<h1>Three</h1>
</When>
</Switch>
// Using 'name' prop
<Switch name="two">
<h1>Default is True</h1>
<h1 slot="one">One</h1>
<h1 slot="two">Two</h1>
<h1 slot="three">Three</h1>
</Switch>
Output
<h1>Two</h1>
A named slot, lets you choose what slot gets rendered, if no slot if passed the default
slot is rendered
<When>
is not required when using this prop
Default: 'default'
Default/fallback slot name
An object that passes arguments to slot functions, use slot names as a key with an argument as its value, requires name
Default: value of default
prop
Key to default/fallback argument when using args
prop
Slot arguments can be passed to any slot function using the name
and args
props
Fallback slot
Expects a <When>
component with a named slot by default, the name does not matter. Slots are checked in order for content, the first slot that contains content will be rendered
You can also use the name
prop to control which slot gets rendered
Using numbers slots and <When>
<Switch>
<h1>Default is True</h1>
<When slot="1" is={false}>
<h1>One is True</h1>
</When>
<When slot="2" is={true}>
<h1>Two is True</h1>
</When>
<When slot="3" is={false}>
<h1>Three is True</h1>
</When>
</Switch>
<h1>Two is True</h1>
---
const one = false;
const two = true;
const three = true;
const four = false;
---
<Switch>
<h1>Default is True</h1>
<When slot="1" {one} {four}>
<h1>One is True</h1>
</When>
<When slot="2" {two} {three}>
<h1>Two is True</h1>
</When>
</Switch>
<h1>Two is True</h1>
Using name
prop and named slots
This example will render a random slot every time it gets rendered
<Switch name={Math.floor(Math.random() * 3)+''}>
<h1>Default is True</h1>
<h1 slot="1">One is True</h1>
<h1 slot="2">Two is True</h1>
<h1 slot="3">Three is True</h1>
</Switch>
You can pass argument to slots using the args
prop
<Switch name="2" args={{
'default': 'Default',
'1': 'One',
'2': 'Two',
'3': 'Three'
}}>
{n => <h1>{n} is True</h1>}
<one slot='1'>{n => <h1>{n} is True</h1>}</one>
<two slot='2'>{n => <h1>{n} is True</h1>}</two>
<three slot='3'>{n => <h1>{n} is True</h1>}</three>
</Switch>
<h1>Two is True</h1>