DEV Community

Rails Designer
Rails Designer

Posted on • Edited on • Originally published at railsdesigner.com

3

Conditionally Add CSS Classes in Your Stimulus Controllers

This article was originally published at Rails Designer

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(" ");
}
Enter fullscreen mode Exit fullscreen mode

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})}"
      />
    `;
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs