How to write, extends and nest CSS classes in JSX?

From the first glance this topic looks ridiculously simple, although if we come closer it has a lot of small caveats and potential errors.


#Use a dedicated library

To reduce amount of errors, unclear output and improve readability of the code, consider using a library like clsx or classnames in the following cases:

  1. You have any conditions, when a certain class name depends on props or state

  2. You have optional class names, which can be undefined

This library (or it’s analogue clsx) provides with a simple and robust syntax to improve your Development Experience and at the same time reduces amount of errors, makes source code cleaner, and output result better.

#Better outputs, less errors

Consider this screenshot of a production environment. What we can see here? An undefined classname, double, tripple and quadriple spaces inside a class attribute. This looks grubby and error prone. Nobody wants an accidental extra classes like undefined!

#Better maintainability, easier to read

With classnames library you can relax and do not care about falsy values, extra spaces, typescript errors of mixing different types into a string. You don’t need to use ternary operators or don’t need to calculate amount of open curly braces.

Consider this example, with dynamic classnames, how easy to spot what makes a certain class to appear.

#clsx vs classname

If you google this phrase it will answer you: “Just use clsx” 😀

The reason behind it is that clsx library has less functionality you don’t know and don’t use anyway and as a result it’s slightly faster and smaller (228 Bytes)

clsx vs classnames
clsx vs classnames

#Use simple className property

Avoid any other properties like customClass, classes, classNames, class or anything else. Assuming you are working with React and use className property for HTML-tags.

#Help with static checking

We will use eslint plugin to forbid class, customClass and parentClass attributes using this rule.