A simple, lightweight yet powerful JavaScript utility function for React
to easily manage CSS classes via the className
attribute.
- 1.: simplified and flexible CSS class management in React
- 2.: multiple, combinable, conditional, and fault tolerant class names from strings, objects, arrays, and functions
- 3.: handles deeply nested arrays, objects, and functions
- 4.: handles class names with leading dots (e.g.:
'.class-name'
=>'class-name'
)
npm i @reactory/class-name
import React from 'react'
import className from '@reactory/class-name'
// Regular use cases
export function Container (props) {
return (
<div
className={className(
'container', // regular CSS class
'.fluid', // CSS class with a leading dot
props.active && 'active', // conditional CSS class
{ shrunken: !props.isStretched }, // conditional CSS class in an object
[ props.isMarked && 'marked' ], // conditional CSS class in an array
)}
>
{props.children}
</div>
)
}
/**
* Built-in deduplication
*
* Classes will be excluded or included from the class list
* based on their falsy or truthy values.
*/
export function Button (props) {
return (
<button
className={className(
// if true, btn-hover class will be added to the class list
{ 'btn-hover': props.isHover },
// ...
// then later, btn-hover will be removed from the class list
{ 'btn-hover': !props.disabled },
// ...
// then again, later will be added again to the class list
{ 'btn-hover': props.isHoverEnforced },
)}
>
{props.label}
</button>
)
}
Any contribution is highly appreciated. To get going, check out the contribution guidelines.
Thank you!