I'm attempting to use the HOCs withInstanceId
(to generate a unique identifier to use as an ID in the HTML) and withColors
(to use a color picker in the sidebar) in Gutenberg and I'm unsure of the correct ESNext syntax. (And I suppose technically the correct non ESNext syntax...)
This is my starting point, but it's clearly not correct:
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { withColors } = wp.editor;
const { withInstanceId } = wp.compose;
registerBlockType( 'blocksetc/test', {
title: __( 'title' ),
attributes: {
highlightColor: {
type: "string"
},
},
edit: withColors( 'highlightColor' )( function ({ attributes, setAttributes, className, instanceId }) {
return (
);
},
save( { attributes } ) {
return (
);
},
} );
A little guidance would be appreciated.
I would suggest using the Gutenberg utilities for composing HOC's. I didn't get the context of your case so I decided that the basic WordPress block example is a good starting point and I combined it with your code to get the following:
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { withColors } = wp.editor;
const { compose, withInstanceId } = wp.compose;
const BaseHtml = ({instanceId, highlightColor}) => {
console.log(highlightColor);
return (<div id={'my-custom-' + instanceId}>Hello World, step 1 (from the editor).</div>)
};
const CombinedComponent = compose(withColors('highlightColor'), withInstanceId)(BaseHtml);
registerBlockType('gutenberg-examples/example-01-basic-esnext', {
title: 'Example: Basic (esnext)',
icon: 'universal-access-alt',
category: 'layout',
attributes: {
highlightColor: {
type: 'string'
},
},
example: {},
edit(props) {
return <CombinedComponent {...props} />;
},
save() {
return <div>Hello World, step 1 (from the frontend).</div>;
},
});
The order of the composed HOC's doesn't matter in this case, but keep in mind that they are executed from right to left. This is described in the Gutenberg compose doc.
Please keep in mind that the core WordPress Gutenberg is not the newest code from the Gutenberg team and I would suggest installing the Gutenberg plugin. You will get useful hints and a more stable codebase with fewer bugs. For example, in your code, with the Gutenberg plugin installed, it logs the following warning: wp.editor.withColors is deprecated. Please use wp.blockEditor.withColors instead.