I don’t understand the benefit of the CSS classes API

Can someone provide a better example than the handbook/reference?

Why would you hard-code these same classes into every element using the same controller? Just to be able to customize the class name but without providing a default?

Doesn’t add any state management of classes to controllers. Purely for reusability?

I see two main reasons for using the classes API:

  • It decouples CSS from controllers.
  • It allows you to use different CSS classes for different use cases (e.g. controller re-usablity).

If you want have a default then you can manually fallback to it in your controller or just hard code the class name in the controller and use it all the time.

1 Like

Thanks for your thoughts.

Yes, I guess decoupling the classes from the controllers has a few benefits, namely paving the way for sharing completely reusable controllers. Better to tell the controller what css class to use rather than adapt your project to predetermined classes.

Perhaps I was thinking too much, searching for something more complex. Ah the beautiful simplicity of Stimulus!

I agree with your points above. I also think it helps prevent mistyping class names. I was going through a controller that had the same class in two spots, once where it was added, and once where it was removed. Adding the CSS class made the code clearer, and I even fixed a bug where I had the wrong class name.

this.editableTarget.classList.remove("editable--hidden");
this.editableTarget.classList.add("editable--hidden");

became

static classes = ["editableHidden"];
this.editableTarget.classList.remove(this.editableHiddenClass);
this.editableTarget.classList.add(this.editableHiddenClass);

Certainly more code, but I like this better, because I will spend less time figuring out what’s going on when I come back to this controller.

Yes, reducing the number of string constants is always a win!