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. 😅
Want to read me more?
-
Conditionally Add CSS Classes in Your Stimulus Controllers
You can cleanup your Stimulus controllers by using a simple vanilla JavaScript function. -
Lesser Known Rails Helpers to Write Cleaner View Code
Rails (ActiveSupport/ActionView) has a wide-range of some great helpers to help you (hah!) write cleaner and more readable code. This articles lists the more obscure ones. -
Data-Attributes Magic with Tailwind CSS & Stimulus
Combine Tailwind data state and Stimulus to create usable UI's easily.
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}}