Rails: Highlight the link for the active page

09 Sep 2023

Rails 6.1 introduced the class_names helper. If you’ve used React or similiar you might already know what that does. It’s nice to see a similar thing included with Rails.

class_names makes it easy to conditionally construct a string of css-classes.

Let’s say you want to make a link bold if it meets some condition. The old way of doing that would be string-interpolation or extract the css classes to a variable inside an if else like so:

<%= link_to "Home", home_path, class: "text-blue-500 #{link_active ? 'font-bold' : ''}" %>

As you can probably tell, that gets messy fast. Doesn’t take too many classes before this gets really hard to read.

class_names to the rescue

class_names makes this a bit better.

We can do something like

<%= link_to "Home", home_path, class: class_names("text-blue-500", "font-bold": link_active) %>

Now font-bold is added as a class when link_active is true, and won’t if it’s not :)

You can even pair this with current_page? so you can do the following:

<%= link_to "Home", home_path, class: class_names("text-blue-500", "font-bold": current_page?(home_path)) %>

Simple as that!