Switch
A control that indicates whether a setting is on or off.
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\SwitchRoot;
use function Phem\Ui\SwitchThumb;
#[Component]
function SwitchHeroDemo(): Node
{
return (
<label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
<SwitchRoot defaultChecked>
<SwitchThumb />
</SwitchRoot>
Notifications
</label>
);
}
Examples#
Labeling a switch#
An enclosing <label> is the simplest labeling pattern:
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\SwitchRoot;
use function Phem\Ui\SwitchThumb;
#[Component]
function SwitchLabelingDemo(): Node
{
return (
<label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
<SwitchRoot>
<SwitchThumb />
</SwitchRoot>
Notifications
</label>
);
}
#
By default, SwitchRoot renders a <span> element to support enclosing labels. Prefer rendering the switch as a native button with nativeButton when using sibling labels (for/id).
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\SwitchRoot;
use function Phem\Ui\SwitchThumb;
#[Component]
function SwitchNativeButtonDemo(): Node
{
return (
<div className="flex items-center gap-2">
<label htmlFor="notifications-switch" className="text-sm text-neutral-950 dark:text-white">Notifications</label>
<SwitchRoot id="notifications-switch" nativeButton>
<SwitchThumb />
</SwitchRoot>
</div>
);
}
Form integration#
Use Field to handle label associations and form integration:
<?phem
use Phem\Attribute\Component;
use Phem\Node;
use Phem\Ui\{Field, SwitchRoot};
use function Phem\Ui\{FieldLabel, Form, SwitchThumb};
#[Component]
function SwitchFormDemo(): Node
{
return (
<Form>
<Field>
<FieldLabel className="flex items-center gap-2 font-normal">
<SwitchRoot name="notifications">
<SwitchThumb />
</SwitchRoot>
Notifications
</FieldLabel>
</Field>
</Form>
);
}
API reference#
Import the components of the family:
use Phem\Ui\SwitchRoot;
use function Phem\Ui\SwitchThumb;SwitchRoot#
A control that turns a setting on and off: Base UI Switch.Root (switch is a reserved word in PHP), on the phem-toggle controller.
Put it in a <label> with its text. A hidden checkbox keeps the state for a form (name, value). Bind it to a bool state of the app with phem:bind: the checkbox gets the bound value, also with nativeButton or uncheckedValue (a bound switch sends no uncheckedValue).
| Prop | Type | Default |
|---|---|---|
defaultChecked | bool | false |
disabled | bool | false |
readOnly | bool | false |
required | bool | false |
name | ?string | null |
value | ?string | null |
uncheckedValue | ?string | null |
form | ?string | null |
nativeButton | bool | false |
checked | ?Bound | null |
children | ?Html | null |
...attrs | array | [] |
SwitchThumb#
The thumb that moves when the switch turns on.
| Prop | Type | Default |
|---|---|---|
...rest | mixed | — |
The source of the examples: examples/ui/Switch.phem.