Conditionally Add CSS Classes to Your Views and Components
With the release of Rails 6.1, the class_names
view helper 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' : '' %>">
But with the class_names
helper, you can do:
<div class="<%= class_names(active: item.for_sale?) %>">
Both output the following HTML (assuming item.for_sale?
returns true):
<div class="active">
More advanced is the following:
class_names("item", { active: item.for_sale?, "out-of-stock": item.out_of_stock? })
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?) %>
Or even shorter, like this:
<%= tag.div class: [active: item.for_sale?] %>
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. 😅
Rails Designer is a professional UI components library for Rails
Get product updates, insights and latest articles in your inbox
Published at . Last updated at . Have suggestions or improvements on this content? Do reach out. Interested in sharing Rails Designer with the Ruby on Rails community? Become an affiliate.
UI components for Ruby on Rails apps
$
99
one-time
payment
-
One-time payment
-
Access to the entire library
-
Built for Ruby on Rails
-
Designed with Tailwind CSS and enhanced with Hotwire
-
Includes free updates (to any 1.x version)