Stimulus Has Class

Let's now specify the exact CSS classes only in the view as it's a better practice to not tightly couple the class name to the controller.

We'll cover the following

In our current code, we are using the is-hidden CSS class to denote hidden status, and we are actually hard-coding the class name inside our controller. For a short class name like is-hidden that’s unlikely to change, it’s not really a big deal, but it’s often considered a better practice not to tightly couple the class name to the controller and specify the exact CSS classes only in the view.

Stimulus 2.0 has a mechanism for this, where we can store the class name as a special data attribute. The name of the data attribute has the form data-<controllerName>-<descriptor>-class, and the value of the attribute is the name of the CSS class being described—typically you’d use a descriptor that describes the role of the CSS class. These class descriptors are usually added to the same DOM element as the controller.

In our case, we’d augment the controller DOM element with a class data attribute:

<section class="day-body"
         id="day-body-<%= schedule_day.day.by_example("2006-01-02") %>"
         data-controller="day-toggle"
         data-day-toggle-hidden-class="is-hidden">

We have a new attribute data-day-toggle-hidden-class, with

  • data
  • the controller name: day-toggle
  • a description of the role of the class: hidden
  • class

As with targets, we have to declare the class in the controller, and we get a getter and an existing property. Then we can use those properties in place of the hard-coded class.

Decoupling the controller

Our new version of the controllers looks like this:

Get hands-on with 1200+ tech skills courses.