2019:
The response to the lake is many helpful. But for this you do not need the npm package. just create somewhere the name classnames function and call it when you need to;
function classnames(obj){ return Object.entries(obj).filter( e => e[1] ).map( e=>e[0] ).join(' '); }
or
function classnames(obj){ return Object.entries(obj).map( ([k,v]) => v?k:'' ).join(' '); }
example
stateClass= { foo:true, bar:false, pony:2 } classnames(stateClass) // return 'foo pony'
inspirational bonus only
you can declare a helper element and take its classList to access the DOMToken List and maybe write something like that
const classes = document.createElement('span').classList; //DOMTokenโList; function classnames(obj){ classes.value = ''; return Object.entries(obj).reduce( (c, [k,v]) => (c.toggle(k,v),c), classes ).value; }
pery mimon Jan 12 '19 at 17:05 2019-01-12 17:05
source share