3

I'm trying to create custom columns block in Gutenberg. Is it possible to add class to the wrapper of the element in the editor based on the attributes? I'd like to switch ??? to class based e.g. columns-4. Otherwise it's not possible to use flex.

<div id="..." class="wp-block editor-block-list__block ???" data-type="my-blocks/column" tabindex="0" aria-label="Block: Single Column">
 <div>
      <div class="this-can-be-set-in-edit-or-attributes">
         ...
     </div>
 </div>

</div>
2
  • If I understand correctly, the existing columns block built in already uses flex
    – Tom J Nowell
    Dec 29 '18 at 0:51
  • @TomJNowell you can't change size of the column there though.
    – Runnick
    Dec 29 '18 at 12:51
6

Actually it can be done with the filter:

const { createHigherOrderComponent } = wp.compose;
const withCustomClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        if(props.attributes.size) {
            return <BlockListBlock { ...props } className={ "block-" + props.attributes.size } />;
        } else {
            return <BlockListBlock {...props} />
        }

    };
}, 'withClientIdClassName' );

wp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withCustomClassName );
1
  • 1
    Shouldn't the callback at the end of wp.hooks.addFilter be withCustomClassName instead withClientIdClassName? Jan 6 '19 at 20:59
0

I think is also possible to manage wrapper classes with useBlockProps. I found this solution in the official Gutenberg doc, here

import { useBlockProps } from '@wordpress/block-editor';

// ...
const blockSettings = {
apiVersion: 2,

// ...

edit: () => {
    const blockProps = useBlockProps( {
        className: 'my-random-classname',
    } );

    return <div { ...blockProps }>Your block.</div>;
},
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.