Combine CSS classes
This vanilla JavaScript function combines a list of classes into one CSS class, which is useful for creating dynamic styles that have shared classes.
const classNames = (...classes) => {return classes.filter(Boolean).join(' ')}
How to use
The className
function's central role is to join strings passed into the function, which the join()
array method is doing. However, you may have also noticed this weird filter(Boolean)
method. This filter boolean trick checks to see if the value passed in is null
before joining.
You can see this function in use to change the styles of a navbar on scroll.