How to Create a Stimulus Toggle Class Controller

Toggling CSS classes on elements is a really common thing to do in webapps. Stimulus makes this really easy. This is the full controller:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static classes = ["toggle"]

  toggle() {

And you use it like this:

<button data-controller="toggle-class" data-toggle-class-toggle-class="show-button">
  Click me

You can pass it multiple classes too, great if you use Tailwind CSS. See this article about toggling multiple classes for more details on how this works.

<button data-controller="toggle-class" data-toggle-class-toggle-class="border-gray-200 shadow-xl" class="border shadow-lg">
  Click me

Published at . Have suggestions or improvements on this content? Do reach out. Interested in sharing Rails Designer with the Ruby on Rails community? Become an affiliate.

UI components for Ruby on Rails apps

$ 99 69 one-time

Get Access
  • One-time payment

  • Access to the entire library

  • Built for Ruby on Rails

  • Designed with Tailwind CSS and enhanced with Hotwire

  • Includes free updates (to any 1.x version)

  • Last update recently