Skip to main content

Nicer utility classes

Jan 11, 2023

More often than not, I have seen two camps of people using tailwind or any other utility-first css library and complaining about how verbose the HTML/JSX gets when using them. Here are a couple of elements on how they look when we use utility

 <h2 class="font-medium inline text-gray-700">
  Nicer utility Classes
</h2>

 <p class="font-normal inline text-gray-500/80 before:[content: '_']">
  Tips on making utility classes read nicer
 </p>

This is easy and nice, but when you start building layouts, it will easily get complex and the number of css classes that you end up adding to the elements will increase.

You can argue saying, browsers don’t care about class names, your users don’t care etc, but as an engineer who is pedantic about keep by code clean and easily readable, here is the approach I’m leaning to follow nowadays.

There is this library called classed-components which allows you to create components for your css classes, if you have used css-in-js libraries before it would feel familiar.

Here is how I would structure the above example

import classed from 'classed-components';

const Title = classed.h2("font-medium inline text-gray-700")

const SubTitle = classed.p("font-normal inline text-gray-500/80 before:[content: '_']")

Now you have components which get css applied to them and you have create an abstraction where your component code looks neat and easy to read.

// component code

import {Title, SubTitle} from ".../components";

<Title>Nicer utility Classes</Title>
<SubTitle>Tips on making utility classes read nicer</SubTitle>

For now I feel this makes me feel easier to reason about the code without worrying about the presentation parts, if I care about the presentation layer I know where to look and make necessary modifications, this also helps in keeping you CSS classes DRY(Don’t repeat yourself).