This is an unpublished draft from 6 years ago. Unpublished until now, that is.
The classnames library is a very handy tool to apply CSS classes conditionally in JavaScript components. Since the output of the function is just a string, this can be composed very well on multiple conditionals layered on on various parts of the code.
For example, consider the following:
import cx from 'classnames';
switch (type) {
case: 'textarea':
const textareaClassNames = cx('text-area', 'text-input', 'invalid': !this.state.valid);
return <textarea className={textareaClassNames} />
default:
const inputClassNames = cx('text-input', 'invalid': !this.state.valid);
return <input type={type} className={inputClassNames} />
}
The class-names are the same except for one extra item in the case of textarea type input field. Until today, I would’ve done something like the above example, since I never bothered to look at the actual output of the call. A quick glance at the source code of the library made it evident that the library would enable composition with output of another classname-generated value (which is a String). So that code can be simplified to:
import cx from 'classnames';
const className = cx('text-input', 'invalid': !this.state.valid);
switch (type) {
case: 'textarea':
return <textarea className={cx(className, 'text-area')} />
default:
return <input type={type} className={className} />
}
Much better.