Handling Class Names in Your Project

mitrich

--

I’ve participated in a few small startups that rely heavily on interns to build their MVPs. These positions are usually unpaid, and the interns primarily gain experience and networking opportunities from them.

However, such startups often don’t pay enough attention to code quality. In this post, I’ll highlight some common issues I’ve encountered and suggest better approaches.

The Problem

A common pattern among beginners is how they handle conditional class names when working with CSS/SCSS modules. Here’s an example:

className={
status === 'active'
? `${styles.button} ${styles.active}`
: `${styles.button}`
}
className={
status === 'disabled'
? styles.disabled
: ''
}

While this works, it can quickly become hard to read and maintain. Thankfully, there’s an easy way to improve this approach.

The Solution: Using the classnames Library

The classnames library provides a helpful utility cn() (or classNames()). This function can concatenate class names and filter out invalid values such as false, undefined, or null.

Let’s refactor the previous examples using classnames:

className={cn(styles.button, status === 'active' && styles.active)}
className={cn(status === 'disabled' && styles.disabled)}

Much cleaner and easier to read, right?

Best Practices for Conditional Class Names

1. Use Boolean Variables for Simple Conditions

When you have just two states, such as enabled and disabled, define a boolean variable to make your code more expressive:

const isDisabled = status === 'disabled';
className={cn(isDisabled && styles.disabled)}

2. Use an Enum or Type for Multiple States

If you have more than two states, you can map them directly to CSS module classes. For example:

type ButtonStatus = 'enabled' | 'disabled' | 'default';
const status: ButtonStatus = 'enabled';

...

className={cn(styles[status])}

This way, your styles are more manageable, and the code remains concise.

Writing Your Own cn Function

If you don’t want to add an extra dependency like classnames, you can implement a basic version of the cn function yourself. Here’s how:

export const cn = (...args: unknown[]): string => 
args.filter(isString).join(' ');

const isString = (value: unknown): value is string =>
typeof value === 'string' && value.length > 0;

This simple utility function filters out non-string values and joins the rest into a single string, mimicking the functionality of the classnames library.

By adopting these approaches, you’ll make your code more readable, maintainable, and scalable. Startups and teams, even those relying on interns, can benefit greatly from cleaner practices like this. Code quality is an investment that pays off in the long run!

--

--

mitrich
mitrich

Written by mitrich

geophysics => construction & design => IT Front-end developer

No responses yet