5

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 Commented Dec 29, 2018 at 0:51
  • @TomJNowell you can't change size of the column there though. Commented Dec 29, 2018 at 12:51

2 Answers 2

7

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? Commented Jan 6, 2019 at 20:59
6

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>; }, }; 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.