babel plugin for automatically adding classnames()
to className
attribute.
transform
<div className={expression}></div>
to
<div className={classNames(expression)}></div>
In React, when you need to render conditionally classNames, you can write code like this:
<button className={`${active ? 'btn-active' : ''} ${disabled ? 'btn-disabled' : ''}`}>
</button>
classnames can help you write clear conditionally classNames:
<button
className={classNames({
'btn-active': active,
'btn-disabled': disabled,
})}>
</button>
This babel plugin will keep you away from writing many classNames
, make the code clean and easy to read.
Install:
npm i babel-plugin-jsx-classnames --save-dev
Use plugin (example .babelrc):
{
"presets": [
"env",
"react"
],
"plugins": [
...
"jsx-classnames"
]
}
Write your jsx:
<button
className={{
'btn-active': active,
'btn-disabled': disabled,
}}>
</button>
It will be transformed to:
import classNames from 'classnames'
<button
className={classNames({
'btn-active': active,
'btn-disabled': disabled,
})}>
</button>