This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Gutenberg colour palette by className

I have run into an issue with the Gutenberg color palette because it always returns the HEX value of the selected color. What I wanted were options to select a color value in the admin, but have a css class string on the frontend with my selection.

Here is a simple React component that does just that. It selects and displays the colors in the admin the same way that native color palette does, but for the frontend, it outputs the provided string as an attribute.

Put this component inside your codebase, but make sure that you have all the imports provided using node_modules.

import { find } from 'lodash';
import { useState } from 'react';
import { getColorObjectByColorValue } from '@wordpress/editor';
import { ColorPalette } from '@wordpress/components';

export function ColorPaletteCustom({
  colors,
  value,
  onChange,
  disableCustomColors = true,
  clearable = false,
  label,
  help,
}) {
  const [color, setColor] = useState(value);

  const colorValue = find(colors, { name: color });

  return (
    <div className="components-base-control">
      {label && <label htmlFor="color-pallete" className="components-base-control__label">{label}</label>}
      <br />
      <ColorPalette
        colors={colors}
        disableCustomColors={disableCustomColors}
        value={typeof colorValue === 'undefined' ? color : colorValue.color}
        onChange={(newColor) => {
          const colorObject = getColorObjectByColorValue(colors, newColor);
          
          setColor(() => newColor);
          onChange(typeof colorObject === 'undefined' ? '' : colorObject.name);
        }}
        clearable={clearable}
      />
      {help && (
        <p className="components-base-control__help">{help}</p>
      )}
    </div>
  );
}

Next, go to your block and import this component inside the InspectorControls component.

 <ColorPaletteCustom
  label={'Color'}
  colors={[
    { name: 'red', color: '#D8262C' },
    { name: 'pink', color: '#F2BCC0' },
    { name: 'black', color: '#000000' },
  ]}
  value={styleColor}
  onChange={
    (event) => props.setAttributes({ styleColor: event })
  }
/>

This component supports all the props that you can use on the Gutenberg color palette the same way, so for detailed documentation, check this link.