Use toggle buttons instead of checkboxes when the action represents an immediate, on-the-spot change, such as enabling or disabling a setting. Toggles are more intuitive for binary states (e.g., On/Off) and provide clear visual feedback about the current state.
Checkbox is better for forms or when multiple selections might be submitted together.
The simplest way to use the Toggle component is to include it in your template with the <zinq:toggle>
tag.
<zinq:toggle />
The Toggle component can be customized in many ways.
The Toggle component can have its own label.
<zinq:toggle>Subscribe</zinq:toggle>
But also you can set the label by using the label
attribute.
<zinq:toggle label="Newsletter">Subscribe</zinq:toggle>
The label for the off state can be set by the offLabel
attribute.
<zinq:toggle offLabel="You are not subscribed">Subscribed!</zinq:switch>
The Toggle component comes in three sizes: default
, sm
, and lg
. By default, the size is default
.
<div class="flex flex-col space-y-3">
<zinq:toggle size="sm">Subscribe</zinq:toggle>
<zinq:toggle>Subscribe</zinq:toggle>
<zinq:toggle size="lg">Subscribe</zinq:toggle>
</div>
The Toggle component state can be changed from any other component. You can simply use Alpine's @click
directive to toggle the state.
Just define an id for the toggle and use the Alpine.store
to change the state.
<zinq:toggle id="my-toggle-id">Subscribe</zinq:toggle>
<div class="mt-4">
<zinq:badge
@click="Alpine.store('zinq_toggles')['my-toggle-id'].isOn = !Alpine.store('zinq_toggles')['my-toggle-id'].isOn"
class="cursor-pointer select-none"
>Toggle</zinq:badge>
</div>
You can set the default state of the toggle by setting the on
attribute.
<zinq:toggle :on="true">Subscribe</zinq:toggle>
You can use the wire:model
directive to bind the Toggle to a Livewire property.
<zinq:toggle wire:model="subscribe">Subscribe</zinq:toggle>
You can also use wire:model.live
to update the model on every state change.
public bool $subscribed = false;
public function render(): string
{
$label = '<zinq:badge ' . ($this->subscribed ? ' success>YES' : ' danger>NO') . '</zinq:badge>';
return <<<HTML
<div>
<div class="mb-4 flex items-center space-x-2"><span>Subscribed:</span> {$label}</div>
<zinq:toggle wire:model.live="subscribed">Subscribe</zinq:toggle>
</div>
HTML;
}
The Toggle component will automatically display validation errors for you when wire:model
attribute is used.
#[Rule('required')]
public bool $subscribed = false;
public function save(): void
{
$this->validate();
}
public function render(): string
{
return <<<HTML
<zinq:form action="save">
<zinq:toggle wire:model="subscribed">Subscribe</zinq:toggle>
<zinq:button>Save to see validation error</zinq:button>
</zinq:form>
HTML;
}
Or you can manually display validation errors by using the error
attribute.
<zinq:toggle error="Please subscribe!">Subscribe</zinq:toggle>