Rails 6.1 introduces class_names helper

Abhay Nikam

By Abhay Nikam

on 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

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

Rails 6.1.0

1>> class_names(active: current_page?(dashboards_path))
2=> "active"
4# Default classes can be added with conditional classes
5>> class_names('navbar', { active: current_page?(dashboards_path) })
6=> "navbar active"
8# class_names helper rejects empty strings, nil, false arguments.
9>> class_names(nil, '', false, 'navbar' {active: current_page?(dashboards_path)})
10=> "navbar active"
1<li class="<%= class_names(active: current_page?(dashboards_path)) %>">
2  <%= link_to "Home", dashboards_path %>

Check out the pull request for more details on this.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.