Switch
Stableboolean toggles
Usage example #
Copy this ERB into a Rails view after installing the component. The snippet below is the same code used by the live preview above.
app/views/.../switch_example.html.erb
<div class="flex items-center gap-3">
<%= render Senren::SwitchComponent.new(name: "demo_switch_a", id: "demo_switch_a", checked: true) %>
<label for="demo_switch_a" class="text-sm">Enable notifications</label>
</div>
Install this component #
Copy the official component into your app
Use this when you want the Senren-maintained implementation copied into app/components/senren.
Terminal
bin/rails senren:add switch
Create a custom component with the same conventions
Use this when you need an app-specific static component that follows Senren's ViewComponent structure.
Terminal
bin/rails generate senren:component switch --no-client
Dependencies are resolved by senren:add:
label.
At a glance #
Category
Forms
Class name
Senren::SwitchComponent
Stimulus
—
Variants
default
Depends on
label
Pairs with
form, label, settings_section
Source #
app/components/senren/switch_component.html.erb
<label class="inline-flex items-center gap-3 cursor-pointer">
<span class="relative inline-flex h-6 w-11 items-center rounded-full bg-[hsl(var(--senren-muted))] has-[:checked]:bg-[hsl(var(--senren-primary))] transition-colors">
<input type="checkbox" role="switch" id="<%= id %>" name="<%= name %>" value="<%= value %>" <%= "checked" if checked %> class="peer sr-only">
<span aria-hidden="true" class="absolute left-0.5 top-0.5 inline-block h-5 w-5 transform rounded-full bg-[hsl(var(--senren-background))] transition-transform peer-checked:translate-x-5"></span>
</span>
<% if label %>
<span class="text-sm font-medium text-[hsl(var(--senren-foreground))]"><%= label %></span>
<% else %>
<%= content %>
<% end %>
</label>
app/components/senren/switch_component.rb
# frozen_string_literal: true
module Senren
class SwitchComponent < BaseComponent
VARIANTS = { default: '' }.freeze
SIZES = { md: '' }.freeze
def initialize(name:, checked: false, value: '1', id: nil, label: nil, class_name: nil, **html)
super(variant: :default, size: :md, class_name: class_name, **html)
@name = name
@checked = checked
@value = value
@id = id || name.to_s.parameterize
@label = label
end
attr_reader :name, :checked, :value, :id, :label
end
end
AI agent rules #
Use for
- +boolean toggles
- +settings
Avoid
- -actions that need confirmation - use button + dialog
Accessibility #
- role=switch with aria-checked.