Rails 6.1 introduces class_names helper

Abhay Nikam

Abhay Nikam

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.

Rails 6.0.0

<li class="<%= current_page?(dashboards_path) ? 'active' : '' %>">
  <%= link_to "Home", dashboards_path %>
</li>

Rails 6.1.0

>> 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.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.