Stimulus Has Class

Let's learn about specifying CSS classes in view and how it affects our application's coupling.

Hidden CSS Class

In our current code, we use the hidden CSS class to denote hidden status, and we are hard-coding the class name inside our controller. For a short class name like hidden, that’s unlikely to change. While application breaking, it’s a best practice to not tightly couple the class name to the controller. Instead, it’s often best to specify the exact CSS classes only in the view. Eventually, we’ll want our controller to have more generic behavior.

Stimulus has a mechanism for this, where we can store the class name as a special data attribute. Essentially, this is a special case of the values attributes. 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, we’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.

Note: This currently doesn’t work well with utility CSS tools like Tailwind, where you are likely to have a set of CSS classes rather than a single one. That said, there is an unreleased change to Stimulus that has already been made, so the set behavior may be available.

What we do is use a special attribute to register the CSS class in the DOM:

Get hands-on with 1200+ tech skills courses.