Search code examples
wordpresswordpress-gutenberggutenberg-blocks

Add a class to the parent .wp-block element in gutenberg editor


When Gutenberg creates a class, it seems to be of the format

div.wp-block
    div.editor-block-list__insertion-point
    div.editor-block-list__block-edit
        div.editor-block-contextual-toolbar
        div
            <your actual block html goes here>

I'd like to be able to add a class to that top div.wp-block element so I can properly style my block in the editor. The class is dynamically generated based on an attribute so I can't just use the block name class. Is there a clean way of doing this? I can hack it using javascript DOM, but it gets overwritten quickly enough.


Solution

  • https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blocklistblock

    const { createHigherOrderComponent } = wp.compose
    
    const withCustomClassName = createHigherOrderComponent((BlockListBlock) => {
      return props => {
        return <BlockListBlock { ...props } className={ 'my-custom-class' } />
      }
    }, 'withCustomClassName')
    wp.hooks.addFilter('editor.BlockListBlock', 'my-plugin/with-custom-class-name', withCustomClassName)