Build HTML class names with BEM syntax without repeating yourself
npm install @henit/bem-classA small, simple tool (without dependencies) for writing class names in BEM-syntax for DOM elements, with a simplified syntax that avoids large amounts of repetition.
```
npm install --save @henit/bem-class
`jsx`
function Button({ className, icon, variant, size, disabled, label }) {
return (
)
}
`jsx
import classLib from 'class-library';
function Button({ className, icon, variant, size, disabled, label }) {
const classNames = classLib(
'button',
button--variant-${variant},button--size-${size}
,
{ 'button--disabled': disabled },
className,
};
return (
)
}
`
`jsx
import bemClass from '@henit/bem-class';
const cn = bemClass('button');
function Button({ className, icon, variant, size, disabled, label }) {
return (
)
}
`
The default export from bem-class is a factory function that takes the block name as argument, and returns a classname-creator function for that block:
`
import bemClass from '@henit/bem-class';
const cn = bemClass('button');
`
The block function returns a class name string ready for use in the DOM.
Three types of arguments can be sent to the created block function (i.e. cn):
- string - Element nameobject
- - Modifiersarray
- - Mix classes
When called without an element (string argument), the block function return the block (with any given modifiers/mixes).
`
cn() // 'button'
cn({ color: 'blue', outlined: true, disabled: false }) // 'button button--color-blue button--outlined'
cn(['save-button']) // 'button save-button'
cn({ color: 'blue' }, ['form-control', 'save-button']) // 'button button--color-blue form-control save-button'
cn('label') // 'button__label'
cn('label', { color: 'blue', outlined: true, disabled: false }) // 'button__label button__label--color-blue button__label--outlined'
cn('label', ['form-label']) // 'button__label form-label'
cn('label', { variant: 'large' }, ['form-label']) // 'button__label button__label--variant-large form-label'
``
And that's it!