Switch

A control that allows the user to toggle between on and off.

Stimulus: shadcn--switch

Installation

Add the component to your project:

rails generate shadcn:component switch

Usage

<div class="flex items-center space-x-2">
  <%= render Shadcn::SwitchComponent.new(id: "airplane-mode") %>
  <%= render Shadcn::LabelComponent.new(for: "airplane-mode") { "Airplane Mode" } %>
</div>

Examples

Default

Checked

Set checked: true to render in the on state.

<div class="flex items-center space-x-2">
  <%= render Shadcn::SwitchComponent.new(id: "checked-switch", checked: true) %>
  <%= render Shadcn::LabelComponent.new(for: "checked-switch") { "Enabled by default" } %>
</div>

Disabled

<div class="flex items-center space-x-2">
  <%= render Shadcn::SwitchComponent.new(id: "disabled-switch", disabled: true) %>
  <%= render Shadcn::LabelComponent.new(for: "disabled-switch") { "Disabled switch" } %>
</div>

In a Form

Notifications

Configure how you receive notifications.

Receive notifications via email.

Receive push notifications.

Receive notifications via SMS.

API Reference

API Reference

Prop Type Default Description
name String nil Input name attribute
id String nil Input id attribute
value String "1" Value when checked
checked Boolean false Whether the switch is on
disabled Boolean false Whether the switch is disabled
required Boolean false Whether the switch is required

Stimulus Controller

This component requires JavaScript. The Stimulus controller docs provides interactivity.

Handles switch toggle state and updates form values.

Installation

Add to your config/importmap.rb:

pin "shadcn-rails", to: "shadcn/index.js"

Then in your app/javascript/controllers/index.js:

import { Application } from "@hotwired/stimulus"
import { registerShadcnControllers } from "shadcn-rails"

const application = Application.start()
registerShadcnControllers(application)

Or import just this controller:

import DocsController from "shadcn-rails/controllers/docs_controller"

application.register("docs", DocsController)

Values

Name Type Default Description
checked Boolean Current checked state
name String Form input name for submission

Actions

Action Description
toggle Toggles the switch state

TypeScript

Type definitions are included. Import types as needed:

import type { DocsController } from "shadcn-rails"

Accessibility

  • Uses role="switch" for proper accessibility
  • Has aria-checked attribute that reflects current state
  • Always pair with a LabelComponent for accessibility
  • Disabled state is properly announced to screen readers
  • Keyboard navigable - can be toggled with Space key