Tailwind CSS responsive classes not working with Rails ViewComponent gem

2.1k views Asked by At

I'm using the ViewComponent gem with Tailwind CSS. I render components from my view files with <%= render ExampleComponent.new(resource: @resource) %>. In my app/components directory, I have example_component.rb and example_component.html.erb files. The component renders fine. But if I have Tailwind CSS classes that use responsive utility variants, it's hit or miss whether or not they work. For example, say I'm rendering using a view component:

# app/components/example_component.rb
class ExampleComponent < ViewComponent::Base
  def initialize(resource:)
    @resource = resource
  end
end

with a view component html.erb file:

# app/components/example_component.html.erb
<%= form_with url: resource_path, target: '_top', class: 'mb-2 md:mb-0' do |f| %>
  <%= f.hidden_field :resource_id, value: @resource.id %>
  <%= f.submit 'Submit', class: "w-full md:w-fit" %>
<% end %>

The Tailwind classes make the bottom margin change from 2 to 0 when the display is medium (md) or larger. Also, the submit button changes from width 100% to width fit-content when the display is medium or larger. If I render this with the usual Rails render from a partial in the views directory, it works fine. If I render the exact same html.erb file using a ViewComponent class, it doesn't recognize the class changes with the "md:" responsive utilities. If I use the Chrome dev tools to inspect the element, it doesn't list the @media classes at all. The "md:" classes are displayed in the element's class, but they aren't listed in the dev tools' style section and they don't work. Another weird thing that happens sometimes is that occasionally these responsive class utilities do work and sometimes they don't. Other times, they work and if I change a value in the responsive class utility and reload the page, it stops working.

Another strange behavior I've noticed is some Tailwind classes aren't working. I have an element with "border-4" in the class which sets the border-width to 4px. It works fine as a Rails partial, but it stops working when I render it with a ViewComponent class. This particular one does start working in the view component if I change it to "border-2" for some reason. Bizare.

2

There are 2 answers

0
Paul On BEST ANSWER

Well, I just figured it out thanks to this reddit post: Bug related to view components and tailwind. I'll leave this here for anyone who has the same issue. In Tailwind's config file tailwind.config.js, the ./app/components directory needs to be added to the directories array under content: Once I added it, everything started working properly.

1
Usama Mahmood On

I faced same issue. In tailwind.config.js add following line to your content:

content: [
  './app/components/**/*.{erb,html}',
],