February 4, 2020
This blog is part of our Rails 6.1 series.
Rails 6.1 adds class_names view
helper method to conditionally add CSS classes. class_names
helper accepts
String, Hash and Array as arguments and returns string of class names built from
arguments.
Before Rails 6.1, conditional classes were added by using conditional statements. Let's take an example of adding an active class to navigation link based on the current page.
<li class="<%= current_page?(dashboards_path) ? 'active' : '' %>">
<%= link_to "Home", dashboards_path %>
</li>
>> class_names(active: current_page?(dashboards_path))
=> "active"
# Default classes can be added with conditional classes
>> class_names('navbar', { active: current_page?(dashboards_path) })
=> "navbar active"
# class_names helper rejects empty strings, nil, false arguments.
>> class_names(nil, '', false, 'navbar', {active: current_page?(dashboards_path)})
=> "navbar active"
<li class="<%= class_names(active: current_page?(dashboards_path)) %>">
<%= link_to "Home", dashboards_path %>
</li>
Check out the pull request for more details on this.
If this blog was helpful, check out our full blog archive.