From the first glance this topic looks ridiculously simple, although if we come closer it has a lot of small caveats and potential errors.
To reduce amount of errors, unclear output and improve readability of the code, consider using a library like
classnames in the following cases:
You have any conditions, when a certain class name depends on
You have optional class names, which can be
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.
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
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.
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)
Avoid any other properties like
class or anything else. Assuming you are working with React and use
className property for HTML-tags.
We will use
eslint plugin to forbid
parentClass attributes using this rule.