Conditionally Add CSS Classes in Your Stimulus Controllers
When you need to create a bit more advanced UI’s in your Rails application, Stimulus is a great, little framework to easily add sprinkles of JavaScript.
Whenever I have some functionality that is reused in multiple Stimulus controllers, I extract them into “helper” functions. I put these (related) functions in their own file in the app/javascript/controllers/helpers/ folder.
A common thing I do, similar to Rails views and components, is conditionally add CSS classes to an element.
For that I use a really simple JavaScript function:
// app/javascript/controllers/helpers/class_names.js
export function classNames(options) {
return Object.keys(options).filter(key => options[key]).join(" ");
}
And then in your Stimulus controller:
import { Controller } from "@hotwired/stimulus";
import { classNames } from "helpers/class_names";
export default class extends Controller {
// …
get tooltipTemplate() {
return `
<span
role="tooltip"
class="${classNames({"tooltip": true, "tooltip--dark": this.isDarkTheme})}"
/>
`;
}
}
The tooltip-span will have the tooltip class by default and the tooltip--dark only when this.isDarkTheme returns true. Getting started is very easy, much like using Rails’ class_names.
Want to read me more?
-
Conditionally Add CSS Classes to Your Views and Components
Using the `class_names` helper in Rails cleans up your views and components drastically. -
How to Properly Structure Stimulus Controller
Guideline on how to properly structure your Stimulus controller. -
How to Create a Stimulus Toggle Class Controller
A simple to use Stimulus controller to toggle classes on an element. Ready to be copied and pasted into your app.
Over to you…
What did you like about this article? Learned something knew? Found something is missing or even broken? 🫣 Let me (and others) know!
Comments are powered by Chirp Form
{{comment}}