Checkbox Group
A set of checkboxes that can require at least one to be checked.
Usage
Example
FormFieldSet do
FormFieldLegend(variant: :label) { "Show these items on the desktop:" }
CheckboxGroup do
FormField(orientation: :horizontal) do
Checkbox(id: "hard_disks", checked: true)
FormFieldLabel(for: "hard_disks", class: "font-normal") { "Hard disks" }
end
FormField(orientation: :horizontal) do
Checkbox(id: "external_disks")
FormFieldLabel(for: "external_disks", class: "font-normal") { "External disks" }
end
FormField(orientation: :horizontal) do
Checkbox(id: "connected_servers")
FormFieldLabel(for: "connected_servers", class: "font-normal") { "Connected servers" }
end
end
end
Required
form(class: "flex flex-col gap-6") do
FormFieldSet do
FormFieldLegend(variant: :label) { "Notifications" }
FormFieldHint { "Pick at least one channel." }
CheckboxGroup(required: true) do
FormField(orientation: :horizontal) do
Checkbox(id: "notify_email", name: "notify[]", value: "email")
FormFieldLabel(for: "notify_email", class: "font-normal") { "Email" }
end
FormField(orientation: :horizontal) do
Checkbox(id: "notify_sms", name: "notify[]", value: "sms")
FormFieldLabel(for: "notify_sms", class: "font-normal") { "SMS" }
end
end
end
Button(type: "submit", class: "w-fit") { "Save" }
end
With error message
form(class: "flex flex-col gap-6") do
FormFieldSet do
FormFieldLegend(variant: :label) { "Topics" }
FormField do
FormFieldHint { "Pick at least one topic." }
CheckboxGroup(required: true) do
div(class: "flex items-center gap-3") do
Checkbox(
id: "topic_rails",
name: "topics[]",
value: "rails",
data: {value_missing: "Pick at least one topic."}
)
FormFieldLabel(for: "topic_rails", class: "font-normal") { "Rails" }
end
div(class: "flex items-center gap-3") do
Checkbox(
id: "topic_hotwire",
name: "topics[]",
value: "hotwire",
data: {value_missing: "Pick at least one topic."}
)
FormFieldLabel(for: "topic_hotwire", class: "font-normal") { "Hotwire" }
end
end
FormFieldError()
end
end
Button(type: "submit", class: "w-fit") { "Save" }
end
Installation
Using RubyUI CLI
Run the install command
rails g ruby_ui:component Checkbox
Manual installation
1
Add RubyUI::Checkbox to app/components/ruby_ui/checkbox/checkbox.rb
# frozen_string_literal: true
module RubyUI
# A checkbox, styled after shadcn's Checkbox (Base UI + vega). Renders a
# native <input type="checkbox"> instead of Base UI's span[role=checkbox]
# plus hidden input. The check mark is the input's ::before (a mask of
# lucide's CheckIcon in text-primary-foreground) and ::after widens the hit
# area, so there is no wrapper and peer-* classes on a following label keep
# working.
#
# indeterminate: true shows the mixed state (minus icon); the browser clears
# it on the first click. readonly: true keeps the value but blocks toggling
# (aria-readonly; the readonly attribute does nothing on checkboxes).
# unchecked_value: renders a hidden input with the same name before the
# checkbox, so the form sends that value when the box is unchecked (Rails'
# check_box pattern).
class Checkbox < Base
BASE = [
"peer relative size-4 shrink-0 appearance-none rounded-[4px] border border-input bg-transparent p-0",
# High contrast: give the drawing back to the browser (as @tailwindcss/forms does).
"forced-colors:appearance-auto forced-colors:checked:before:hidden forced-colors:indeterminate:before:hidden",
"text-inherit shadow-xs transition-shadow outline-none dark:bg-input/30",
"after:absolute after:-inset-x-3 after:-inset-y-2",
"before:pointer-events-none before:absolute before:inset-0 before:m-auto before:hidden before:size-3.5",
"before:bg-current before:[mask-position:center] before:[mask-repeat:no-repeat] before:[mask-size:100%]",
"focus:ring-0 focus:ring-offset-0 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
"disabled:cursor-not-allowed disabled:opacity-50 group-has-disabled/field:opacity-50",
"aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-disabled:pointer-events-none",
"aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20",
"dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
# Checked: lucide CheckIcon.
"checked:border-primary checked:bg-primary checked:bg-none checked:text-primary-foreground",
"dark:checked:bg-primary aria-invalid:checked:border-primary checked:before:block",
"checked:before:[mask-image:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M20%206%209%2017l-5-5%22%2F%3E%3C%2Fsvg%3E)]",
# Indeterminate: lucide MinusIcon (the indeterminate variant comes after checked, so it wins).
"indeterminate:border-primary indeterminate:bg-primary indeterminate:bg-none indeterminate:text-primary-foreground",
"dark:indeterminate:bg-primary indeterminate:before:block",
"indeterminate:before:[mask-image:url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M5%2012h14%22%2F%3E%3C%2Fsvg%3E)]"
].freeze
ACTIONS = "change->ruby-ui--checkbox-group#onChange change->ruby-ui--form-field#onInput invalid->ruby-ui--form-field#onInvalid ruby-ui--checkbox-group:change->ruby-ui--form-field#onChange"
def initialize(indeterminate: false, readonly: false, unchecked_value: nil, **attrs)
@indeterminate = indeterminate
@readonly = readonly
@unchecked_value = unchecked_value
super(**attrs)
raise ArgumentError, "unchecked_value: needs name:" if !@unchecked_value.nil? && !attrs[:name]
end
def view_template
unless @unchecked_value.nil?
input(type: "hidden", name: attrs[:name], value: @unchecked_value.to_s, disabled: attrs[:disabled], form: attrs[:form], autocomplete: "off")
end
input(**attrs)
end
private
def default_attrs
{
type: "checkbox",
aria: (@readonly ? {readonly: "true"} : {}),
data: {
slot: "checkbox",
ruby_ui__form_field_target: "input",
ruby_ui__checkbox_group_target: "checkbox",
**controller_data
},
class: BASE
}
end
# The checkbox controller is only needed for indeterminate (a JS-only
# property) and readonly (blocking the toggle).
def controller_data
return {action: ACTIONS} unless @indeterminate || @readonly
{
controller: "ruby-ui--checkbox",
ruby_ui__checkbox_indeterminate_value: @indeterminate.to_s,
ruby_ui__checkbox_readonly_value: @readonly.to_s,
action: "click->ruby-ui--checkbox#guard change->ruby-ui--checkbox#sync #{ACTIONS}"
}
end
end
end
2
Add RubyUI::CheckboxDocs to app/components/ruby_ui/checkbox/checkbox_docs.rb
# frozen_string_literal: true
class Views::Docs::Checkbox < Views::Base
def view_template
component = "Checkbox"
div(class: "max-w-2xl mx-auto w-full py-10 space-y-10") do
render Docs::Header.new(title: "Checkbox", description: "A control that allows the user to toggle between checked and not checked.")
Heading(level: 2) { "Usage" }
render Docs::VisualCodeExample.new(title: "Example", context: self) do
<<~RUBY
div(class: "flex items-center gap-3") do
Checkbox(id: "terms")
FormFieldLabel(for: "terms") { "Accept terms and conditions" }
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Checked", context: self) do
<<~RUBY
div(class: "flex items-start gap-3") do
Checkbox(id: "terms_checked", checked: true)
div(class: "grid gap-2") do
FormFieldLabel(for: "terms_checked") { "Accept terms and conditions" }
p(class: "text-sm text-muted-foreground") { "By clicking this checkbox, you agree to the terms and conditions." }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Indeterminate", description: 'The mixed state, for example a "select all" box. The browser clears it on the first click.', context: self) do
<<~RUBY
div(class: "flex items-center gap-3") do
Checkbox(id: "select_all", indeterminate: true)
FormFieldLabel(for: "select_all") { "Select all" }
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Disabled", context: self) do
<<~RUBY
div(class: "flex items-center gap-3") do
Checkbox(id: "toggle_disabled", disabled: true)
FormFieldLabel(for: "toggle_disabled") { "Enable notifications" }
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Invalid", context: self) do
<<~RUBY
div(class: "flex items-center gap-3") do
Checkbox(id: "terms_invalid", aria: {invalid: "true"})
FormFieldLabel(for: "terms_invalid") { "Accept terms and conditions" }
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Read only", description: "Keeps its value and is submitted with the form, but can't be toggled.", context: self) do
<<~RUBY
div(class: "flex items-center gap-3") do
Checkbox(id: "terms_readonly", name: "terms_accepted", value: "1", checked: true, readonly: true)
FormFieldLabel(for: "terms_readonly") { "Accepted on sign up" }
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Unchecked value", description: "unchecked_value: renders a hidden input with the same name before the checkbox, so the form also sends a value when the box is unchecked (like Rails' check_box).", context: self) do
<<~RUBY
div(class: "flex items-center gap-3") do
Checkbox(id: "user_admin", name: "user[admin]", value: "1", unchecked_value: "0")
FormFieldLabel(for: "user_admin") { "Admin" }
end
RUBY
end
render Components::ComponentSetup::Tabs.new(component_name: component)
render Docs::ComponentsTable.new(component_files(component))
end
end
end
3
Add RubyUI::CheckboxGroup to app/components/ruby_ui/checkbox/checkbox_group.rb
# frozen_string_literal: true
module RubyUI
# shadcn has no CheckboxGroup: its checkbox groups are a
# FieldGroup with data-slot="checkbox-group". RubyUI keeps a component for
# the group-level `required` (at least one checked), which neither shadcn
# nor native HTML provides.
class CheckboxGroup < Base
def initialize(required: false, **user_attrs)
@required = required
super(**user_attrs)
end
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
role: "group",
data: {
slot: "checkbox-group",
controller: "ruby-ui--checkbox-group",
required: (true if @required)
},
class: "group/field-group @container/field-group flex w-full flex-col gap-3"
}
end
end
end
4
Add checkbox_controller.js to app/javascript/controllers/ruby_ui/checkbox_controller.js
import { Controller } from "@hotwired/stimulus";
// Wired by RubyUI::Checkbox only when indeterminate: or readonly: is set.
export default class extends Controller {
static values = { indeterminate: Boolean, readonly: Boolean };
// indeterminate has no HTML attribute: it is a property of the input.
indeterminateValueChanged(value) {
this.element.indeterminate = value;
}
// Click covers mouse, Space and clicks on an associated <label>.
guard(event) {
if (this.readonlyValue) event.preventDefault();
}
// The browser clears indeterminate on toggle; keep the value in step so a
// reconnect doesn't bring it back.
sync() {
if (this.indeterminateValue && !this.element.indeterminate) this.indeterminateValue = false;
}
}
5
Add checkbox_group_controller.js to app/javascript/controllers/ruby_ui/checkbox_group_controller.js
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static targets = ["checkbox"];
connect() {
this.#handleRequired();
}
onChange() {
this.#handleRequired();
if (!this.element.hasAttribute("data-required")) return;
// Toggling `required` changes every checkbox's validity, not only the one
// the user clicked. When each checkbox sits in its own FormField (shadcn's
// Field orientation="horizontal"), tell each field to re-check its state.
this.checkboxTargets.forEach((checkbox) =>
this.dispatch("change", { target: checkbox, bubbles: false }),
);
}
#handleRequired() {
if (!this.element.hasAttribute("data-required")) return;
const checked = this.checkboxTargets.some(({ checked }) => checked);
this.checkboxTargets.forEach((checkbox) => (checkbox.required = !checked));
}
}
6
Update the Stimulus controllers manifest file
Importmap!
You don't need to run this command if you are using Importmap
rake stimulus:manifest:updateComponents
| Component | Built using | Source |
|---|---|---|
Checkbox | Phlex | |
CheckboxDocs | Phlex | |
CheckboxGroup | Phlex | |
CheckboxController | Stimulus JS | |
CheckboxGroupController | Stimulus JS |