Search code examples
javascriptwordpresswordpress-gutenberg

How do I get the color from Wordpress Gutenberg ColorPicker to save correctly?


When creating a Gutenberg block type in wordpress I want the color value to be saved in an attribute and the ColorPicker to start at that color on refreshing of the page but the saved color value doesn't seem to be loaded to the ColorPicker on refresh/reload of page. How do I make the ColorPicker start with the saved color?

const { registerBlockType } = wp.blocks;
const { createElement, Fragment } = wp.element;
const { InspectorControls } = wp.editor;
const { ColorPicker, PanelBody, PanelRow } = wp.components;
const { __ } = wp.i18n;

registerBlockType( 'test/colorpicker', {
    title: 'ColorPicker',
    category: 'layout',
    description: __( 'Testing the ColorPicker' ),
    icon: 'universal-access-alt',
    attributes: {
        color: {
            type: 'array',
        }
    },
    example: {},
    edit: ( { attributes, setAttributes, className } ) => {
        const { color } = attributes;
        return  ([
                <InspectorControls>
                    <Fragment>
                        <PanelBody
                            title={ __('Color Picker', 'test' ) }
                            initialOpen={ true }
                        >
                            <PanelRow>
                                <ColorPicker 
                                  color={ color }
                                  onChangeComplete={ (value) => setAttributes({color:value}) }
                                />
                            </PanelRow>
                        </PanelBody>
                    </Fragment>
                </InspectorControls>,
                <div
                    className={ className }
                    style={{
                        height: '400px'
                    }}
                >
                </div>
                ])
    },
    //Render in PHP
    save: (props) => { return null }
} );

Solution

  • The value passed from the ColorPicker component is an Object and not an Array, so your edit function is not receiving it properly. It is confusing for me as well. Console logging the value from the onChangeComplete function of the ColorPicker will give you a hint.

    You need to change the attributes specification, when registering your block, like so:

    attributes: {
        color: {
            type: 'object' // <== Not 'array'
        }
    }
    

    Hope this helps!