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:
Get hands-on with 1400+ tech skills courses.