---
title: "Rails 6.1 introduces class_names helper"
description:
  "Rails 6.1 introduces class_names helper to conditionally add CSS classes."
canonical_url: "https://www.bigbinary.com/blog/rails-6-1-introduces-class_names-helper"
markdown_url: "https://www.bigbinary.com/blog/rails-6-1-introduces-class_names-helper.md"
---

# Rails 6.1 introduces class_names helper

Rails 6.1 introduces class_names helper to conditionally add CSS classes.

- Author: Abhay Nikam
- Published: February 4, 2020
- Categories: Rails 6.1, Rails

Rails 6.1 adds [class_names](https://github.com/rails/rails/pull/37918) 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

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

#### Rails 6.1.0

```ruby
>> 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"
```

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

Check out the [pull request](https://github.com/rails/rails/pull/37918) for more
details on this.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-1-introduces-class_names-helper)
