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() {
    this.element.classList.toggle(...this.toggleClasses)
  }
}

And you use it like this:

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

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
</button>
Get UI & Product Engineering Insights for Rails Apps (and product updates!)

Published at . Have suggestions or improvements on this content? Do reach out.

UI components for Ruby on Rails apps

$ 129 one-time
payment

Get Access
  • One-time Payment

  • Access to the Entire Library

  • Built for Ruby on Rails (inc. Rails 8)

  • Designed with Tailwind CSS and Enhanced with Hotwire

  • Updates for 12 months