With Tailwind's JIT release, developers can act up HTML elements that are in a specific state. The only class is practical addition to display a HTML element if it has no sibling HTML elements. Under the tailwind-hood, the only class translates into the only-child selector.
Imagine you want to display content only if it is stored in the database. The initial step is to create a conditional statement to render parts of the HTML based on the condition you provide. In the rails example below, the conditional check is
@tasks.empty?. If the
@tasks collection is empty, the empty state message is displayed.
<ul> <% if @tasks.empty? %> <% @tasks.each do |task| %> <%= render "task/task", task: task %> <% end %> <% else %> <p class="block">All tasks completed.</p> <% end %> </ul>
Now, although the code above definitely works, you have added a(nother) conditional to your code.
An alternative is to handle this natively with CSS.
<ul> <% @tasks.each do |task| %> <%= render "task/task", task: task %> <% end %> <p class="hidden only:block">All tasks completed.</p> </ul>
The empty state's element (p-tag) has a default state of hidden. The added only class change the display status to block when the element has no siblings.
Or leverage the rails collection renderer to re-factor your code into:
<ul> <%= render @tasks %> <p class="hidden only:block">All tasks completed.</p> </ul>