JavaScript for WordPress › Forums › Gutenberg Development › How to get a color class name › Reply To: How to get a color class name
Did anyone ever find a final / current answer on this? My JS is basic so this might not be the best way to do this, but it’s working now (which is better than inlining the style colors.
function colorObject(colors, color, prop){
var colorObj = getColorObjectByColorValue(colors, color)
if (typeof colorObj === 'undefined'){
return color.slice(1);
}
switch(prop) {
case 'color':
if ( colorObj.color ){
return colorObj.color
}
return '';
case 'name':
if ( colorObj.name ){
return colorObj.name
}
return '';
case 'slug':
if ( colorObj.slug ){
return colorObj.slug
}
return '';
default:
return ''
}
}
Then for classnames I have something like this:
const classes = classnames(
className,
{
[ <code>block-color-${colorObject(myObj.blockColors, blockColor, "slug") }</code>]: blockColor,
});
Where myObj is an object of settings / values that I pass in via the WP PHP function localize script. This is allowing me to set the colors at the color pallet level, instead of a global one size fits all list of colors (via theme suppprts()). That same obj + property is also used then I configure the various pallets in the inspector.
Maybe there’s a better way to do this? If so, some one please let me know. TIA