If you know all of the classes when you’re writing the code, you can just write them:
But what if you don’t know all of the classes up front because you have to merge in caller-supplied classes? With ES2015, you can use string interpolation:
This works, unless the caller doesn’t supply a class. Suddenly, you’ve got elements with a class of
Or what if you have to conditionally include a class based on some condition? Things can get out of hand in a hurry.
Enter Jed Watson’s classnames library.
classnames handles all of these cases:
classnames takes a list of classes, arrays, or objects. It flattens the arrays and ignores any falsy classes. For objects, it treats each property of the object as a class and only includes the ones whose values are truthy.
This makes for a really clear specification of what classes will be used and eliminates the
undefined class I mentioned above.
What about dynamic classes, such as when using CSS modules?
All in all,
classnames is a really useful part of my toolkit and has quickly become one of my favorite libraries.