Search code examples
wordpresswordpress-gutenberggutenberg-blocks

How to fix the "This block contains unexpected or invalid content" error


Any help would be much appreciated!!

I'm attempting to build a custom Gutenberg block. It works fine initially, but after refreshing the page, I get the "This block contains unexpected or invalid content" error.

I've checked out some other threads but to no avail...

The plugin.php code:

<?php

function loadMyBlock() {
  wp_enqueue_script(
    'columns-block',
    plugin_dir_url(__FILE__) . 'wm-script-final.js',
    array('wp-blocks','wp-editor'),
    true
  );
}

add_action('enqueue_block_editor_assets', 'loadMyBlock');

The JS:


var el = wp.element.createElement,
registerBlockType = wp.blocks.registerBlockType,
RichText = wp.editor.RichText;

registerBlockType( 'md-custom-block/columns-block', {
title: 'Transcript Block',
icon: 'universal-access-alt',
category: 'layout',
attributes: {
content1: {
type: 'array',
source: 'children',
selector: 'div'
},

},
edit: function( props ) {
var attributes = props.attributes;

    function onChangeContentFirst( newContent ) {
        props.setAttributes( { content1: newContent } );
    }



    return (
        el( 'div', { className: 'transcript-block'},
            el(
                RichText,
                {
                    tagName: 'p',
                    className: "none",
                    onChange: onChangeContentFirst,
                    value: attributes.content1
                }
            )

        )
    )
},
save: function( props ) {
    var attributes = props.attributes;
    return(
        el( 'div', { className: 'transcript-block'},
            el( RichText.Content,
                {
                    tagName: 'p',
                    className: props.className,
                    value: attributes.content1
                }
            )

        )
    )
}
} );

Solution

  • When the block is first loaded in the editor, it reads all the properties then calculates the output of the save() function. If the input and the output doesn't match, Gutenberg knows something is wrong and outputs the invalid content error.

    The problem is likely this:

    content1: {
        type: 'array',
        source: 'children',
        selector: 'div'
    }
    

    You have made the selector the div, but the content was actually output in the p so the content isn't matching up with what was saved.

    You need to either change that selector or remove the p from the save function.