Created
September 2, 2017 11:25
-
-
Save tenphi/dfde26cf5f8ecbfdc5d3733fff71ae38 to your computer and use it in GitHub Desktop.
BEM-class Generator for 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
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