Last active
March 23, 2018 17:18
-
-
Save gaearon/84f04ff35334ed80dcaf to your computer and use it in GitHub Desktop.
BEM in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var React = require('react'), | |
classSet = require('react/lib/cx'), | |
_ = require('underscore'); | |
var ClassNameMixin = { | |
propTypes: { | |
className: React.PropTypes.string, | |
context: React.PropTypes.string | |
}, | |
getClassName() { | |
var componentClassName = this.className || this.constructor.displayName, | |
classNames = [componentClassName], | |
context = this.props.context, | |
modifiers; | |
if (this.getCSSModifiers) { | |
modifiers = this.getCSSModifiers(); | |
} else { | |
modifiers = []; | |
} | |
if (_.isObject(modifiers) && !_.isArray(modifiers)) { | |
modifiers = classSet(modifiers).split(' '); | |
} | |
if (context) { | |
modifiers.push('isIn' + context[0].toUpperCase() + context.slice(1)); | |
} | |
if (this.props.className) { | |
classNames = classNames.concat(this.props.className.split(' ')); | |
} | |
classNames = _.union( | |
classNames, | |
_.compact(modifiers).map(m => componentClassName + '--' + m) | |
); | |
return classNames.join(' '); | |
} | |
}; | |
module.exports = ClassNameMixin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, class name is only used for root selectors (for components themselves). Children selectors (
Something-somePart
) stay greppable.