classnames
Created: 2018-05-02 16:17:45 -0700 Modified: 2018-05-02 16:21:46 -0700
Background (reference)
Section titled Background (reference)This conditionally joins CSS classes together.
Troubleshooting
Section titled TroubleshootingUndefined CSS classes in your DOM
Section titled Undefined CSS classes in your DOMFirst of all, Chrome can search based on class names if you include a period at the beginning of your search term, e.g. “.undefined”, so you can see if this is happening to you pretty quickly.
The cause is this issue:
As shown above, if “this.props.className” isn’t defined, then you’ll get “undefined” showing up in the DOM.
There are multiple solutions/workarounds:
- Fork the library and change the behavior here. The only issue is that “undefined” is a valid CSS class, so you need to make sure not to coerce the string “undefined” into the value undefined.
- In the specific case above, since there is no condition (i.e. they’re both true), switch to the non-object version: classNames(styles.pregameHeader, this.props.className) and it will automatically ignore undefined values.
- Only include the value if it exists, e.g.
classNames({[this.props.className]: !_.isNil(this.props.className)});
- Specify a default prop