I am developing a custom Gutenberg block with the PanelColorSettings component to set up the background color, here is my code
<PanelColorSettings
title={ __( 'Color Settings' ) }
colorSettings={ [
{
value: backgroundColor,
onChange: ( colorValue ) => setAttributes( { backgroundColor: colorValue } ),
label: __( 'Background Color' ),
},
] }
>
</PanelColorSettings>
How do I the color name instead of the color code for the backgroundColor attribute? It seems the default returned value is the color code which is useless in future color code updates as the content would need to be re-saved.
I am developing a custom Gutenberg block with the PanelColorSettings component to set up the background color, here is my code
<PanelColorSettings
title={ __( 'Color Settings' ) }
colorSettings={ [
{
value: backgroundColor,
onChange: ( colorValue ) => setAttributes( { backgroundColor: colorValue } ),
label: __( 'Background Color' ),
},
] }
>
</PanelColorSettings>
How do I the color name instead of the color code for the backgroundColor attribute? It seems the default returned value is the color code which is useless in future color code updates as the content would need to be re-saved.
Share Improve this question asked Oct 15, 2018 at 12:21 Liuta OvidiuLiuta Ovidiu 111 silver badge3 bronze badges2 Answers
Reset to default 2I could solve it with the function getColorObjectByColorValue (take a look at the gutenberg files).
If you have something like
const backgroundColors = [
{
name: 'Light Green',
slug: 'light-green',
color: '#E6F0F0'
},
{
name: 'Light Gray',
slug: 'light-gray',
color: '#F7F7F7'
}
];
then you can get the color name by
const test = getColorObjectByColorValue(backgroundColors, backgroundColor);
console.log(test.name);
Should also work with the default palette.
thanks to: https://javascriptforwp/forums/topic/how-to-get-a-color-class-name/ , Note: wp.editor.getColorObjectByColorValue is deprecated now using wp.blockEditor.getColorObjectByColorValue
const { select } = wp.data;
const { getColorObjectByColorValue} = wp.blockEditor;
function onChangeColor ( color ) {
colorName = '';
if( color ) {
const settings = select( 'core/editor' ).getEditorSettings();
const colorObject = getColorObjectByColorValue( settings.colors, color );
if( colorObject ) {
colorName = colorObject.slug;
}
}
props.setAttributes({color: color});
props.setAttributes({colorName: colorName});
}