• I am writing a custom block (currently using WordPress 5.7). I included a “styles” section in block registration:

            styles: [
    		{
    			name: 'gallery-thumbnail',
    			label: __( 'Thumbnail', 'rosmaplug1' ),
    			isDefault: true
    		},
    		{
    			name: 'gallery-menu',
    			label: __( 'Image menu', 'rosmaplug1' )
    		},
    	],

    This correctly made the block styles menu available and it looked OK but when I hovered over either of the options on it an exception occurred:

    blocks.js?ver=9ed25ffa009c799f99a4340915b6dc6a:7852 Uncaught TypeError: Cannot read property 'map' of undefined
        at cloneBlock (blocks.js?ver=9ed25ffa009c799f99a4340915b6dc6a:7852)
    ...

    The failure in cloneBlock occurs in this code:

        innerBlocks: newInnerBlocks || block.innerBlocks.map(function (innerBlock) {
          return cloneBlock(innerBlock);

    …because block.innerBlocks is not defined. In my case it should be an empty array because I don’t have any inner blocks.

    The workaround is to include an “example” section in the block registration:

    	example: {
    		attributes: {
    			category: '1'
    		},
    	},

    Without the example section the category attribute is being correctly set to ‘1’ (its default), but other values, possibly not limited to innerBlocks, are not being set up.

    Adding the example section in this case shouldn’t make any difference but it results in everything being set up correctly.

    I haven’t tried it but my guess is that the example section is therefore required when using the styles section, even if there are no attributes to set.

    Presumably cloneBlock() should be written more defensively, and maybe also block should be set up properly for block styles menu even is the example section doesn’t exist.

Viewing 1 replies (of 1 total)
  • Thread Starter smeeds

    (@smeeds)

    It seems that this problem applies only when the Block Style Menu is accessed from the Block Toolbar and not when it is accessed from the Settings Sidebar.

    • This reply was modified 3 years, 11 months ago by smeeds. Reason: Typos
Viewing 1 replies (of 1 total)
  • The topic ‘Block registration: “styles” depends on “example”’ is closed to new replies.