Simon
Simon

Reputation: 584

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.

Upvotes: 2

Views: 3220

Answers (2)

Mehmood Ahmad
Mehmood Ahmad

Reputation: 657

You can add class in your block edit view by using className that is present in this.props, className will print class in following format wp-blocks-[block_name]

edit( { className } ) { // using destructing from JavaScript ES-6
  return <div className={ className }></div>
}

Suggestion

Always try to look for manipulating DOM via React instead of manipulating DOM directly because React manages it's own state and issues can occur by manipulating DOM directly.

Upvotes: 0

Rice_Crisp
Rice_Crisp

Reputation: 1261

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)

Upvotes: 2

Related Questions