1

I'm using a filter in the Block API to add a class name to a block's wrapper. I have to add the class name to a specific block, not all blocks.

I tried:

const addClassName = createHigherOrderComponent( ( BlockListBlock ) => {    
  return ( props, blockType ) => {      
    if ( blockType.name === 'myplugin/myblock' ) {
        return <BlockListBlock { ...props } className="test" />;
    }
    return <BlockListBlock { ...props } />
  }
}, 'addClassName' );

wp.hooks.addFilter( 'editor.BlockListBlock', 'myplugin/add-class-name', addClassName );

The issue: blockType.name returns undefined. I also tried getBlockType.name and it also returns undefined. I also tried getting the block name of core blocks. For example core/columns.

2

From the props object we can get the block information. The object contains the name property you are looking for; this would be the code:

const addClassName = createHigherOrderComponent(BlockListBlock => {
    return props => {
        if (props.name === "myplugin/myblock") {
            return <BlockListBlock {...props} className="test" />;
        }
        return <BlockListBlock {...props} />;
    };
}, "addClassName");

wp.hooks.addFilter(
    "editor.BlockListBlock",
    "myplugin/add-class-name",
    addClassName
);
  • 1
    Glad it worked. – Alvaro Mar 6 at 0:32
0

You can get the selected block name by using this wp.data.select( 'core/editor' ).getSelectedBlock().name; inside the block edit or save function. This is the answer of what your question title is saying.

By the way you can easily add class anywhere in the layout inside edit function so why are you hassling so much.

  • This is for a filter which is not added in the edit or save function. – CyberJ Mar 5 at 16:34
  • Where did you find getSelectedBlock? it does not seem to be a gutenberg function. – CyberJ Mar 11 at 13:48
  • It's a gutenberg function which gives you the name of block only if the block was selected. For confirmation on editor screen select any block, open your console and write the code and press enter. – Mehmood Ahmad Mar 11 at 17:28

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.