Stimulus Has Class
Discover how to use Stimulus's has class feature to manage CSS class names outside the controller in Rails. Learn why decoupling CSS classes improves maintainability and supports dynamic styling controlled by Rails views. This lesson helps you implement this best practice using data attributes and TypeScript declarations.
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>-<descr ...