Skip to content

Instantly share code, notes, and snippets.

@tenphi
Created September 2, 2017 11:25
Show Gist options
  • Save tenphi/dfde26cf5f8ecbfdc5d3733fff71ae38 to your computer and use it in GitHub Desktop.
Save tenphi/dfde26cf5f8ecbfdc5d3733fff71ae38 to your computer and use it in GitHub Desktop.
BEM-class Generator for React
import classNames from 'classnames';
// modName -> mod_name
function toKebabCase(str) {
return str ? str.replace(/[A-Z]/g, function(s) {return '-' + s.toLowerCase() }).replace(/$\-/, '') : '';
}
function BEM(blockName) {
blockName = blockName || '';
function block(newBlockName, mods = [], ...classes) {
if (typeof newBlockName === 'string') {
blockName = newBlockName;
}
let blockClass = blockName;
if (mods) {
mods = classNames(mods).split(' ').filter( mod => mod ).map( mod => {
return blockClass + '--' + toKebabCase(mod);
}).join(' ');
}
return { className: [blockClass, mods, classNames(classes)].join(' ').trim() };
}
function elem(elemName, mods = [], ...classes) {
let elemClass = blockName + '__' + elemName;
if (mods) {
mods = classNames(mods).split(' ').filter( mod => mod ).map( mod => {
return elemClass + '--' + toKebabCase(mod);
}).join(' ');
}
return { className: [elemClass, mods, classNames(classes)].join(' ').trim() };
};
return { block, elem };
}
export default BEM;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment