DEV Community

Rails Designer
Rails Designer

Posted on • Originally published at railsdesigner.com

1

Conditionally Add CSS Classes to Your Views and Components

This article was originally published at Rails Designer

With the release of Rails 6.1, the class_names view helpers was introduced. It is one of those helpers I use a lot.

Before you had to write some hard to read code:

<div class="<⁠%= item.for_sale? ? 'active' : '' %>">
Enter fullscreen mode Exit fullscreen mode

But with the class_names helper, you can do:

<div class="<⁠%= class_names(active: item.for_sale?) %>">
Enter fullscreen mode Exit fullscreen mode

Both output the following HTML (assuming item.for_sale? returns true):

<div class="active">
Enter fullscreen mode Exit fullscreen mode

More advanced is the following:

class_names("item", { active: item.for_sale?, "out-of-stock": item.out_of_stock? })
Enter fullscreen mode Exit fullscreen mode

Here item is applied in all cases. And active / out-of-stock only when the respective conditionals are met.

The class_names helper is also supported in tag-helpers. So this works just the same:

<%= tag.div class: class_names(active: item.for_sale?) %>
Enter fullscreen mode Exit fullscreen mode

Or even shorter, like this:

<%= tag.div class: [active: item.for_sale?] %>
Enter fullscreen mode Exit fullscreen mode

It's one of those little, unknown features in Rails that helps you write better views and components. No wonder it is used in almost all Rails Designer's components.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay