In Gutenberg, the markup from the edit
function is wrapped in a few other elements. The outer wrapper of each block has the wp-block
class and a data-block
attribute that contains the name of the block with its namespace – core/group
for the group block, for example.
We can change the attributes of that wrapper, so we could add class names depending on the selected/changed block options, what could make the styling of blocks in the backend easier.
A way that works for all blocks is the editor.BlockListBlock
filter. To add a class name that contains the value of an attribute, we could do the following (solution highly inspired by a StackExchange answer):
const { createHigherOrderComponent } = wp.compose;
const withStyleClasses = createHigherOrderComponent( ( BlockListBlock ) => {
return ( props ) => {
if ( props.name !== 'my/block' ) {
return <BlockListBlock { ...props } />
}
const {
myAttribute,
} = props.attributes;
return <BlockListBlock { ...props } className={ `my-attribute-${ myAttribute }` } />;
};
}, 'withStyleClasses' );
wp.hooks.addFilter( 'editor.BlockListBlock', 'slug/with-style-classes', withStyleClasses );
Code language: JavaScript (javascript)
The withStyleClasses
function, that is hooked to the editor.BlockListBlock
filter gets the BlockListBlock
as a parameter. Inside the function, we check if the block identifier is my/block
, otherwise we return BlockListBlock
without any modifications.
If we have the wanted block, we get the value of the myAttribute
attribute and add a class name that begins with my-attribute-
followed by the current value of the attribute.
Another way that I found works with getEditWrapperProps
when registering a block, but is, at least in my tests, not usable for things like additional classes (because it did not work to add the class to existing ones but only replace existing ones with the new class). But it seems to be very useful for additional data-
attributes.