WordPress/Gutenberg block example preview don't work

Viewed 911

I use Gutenberg with WordPress.

I'm trying to use example property to show an image in the block preview area. But I got a preview of a block itself (this is not my image but how the field is in the editor).

https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/#example-optional

What's wrong please ? Can I have some help ?

enter image description here

registerBlockType( 'ccn/gut-text-title', {
    apiVersion: 2,
    title: __( 'Titre', 'ccn-gut' ),
    category: 'text',
    icon: blockIcons.text_title,
    keywords: [ __( 'titre', 'ccn-gut' ) ],
    attributes: {
        content: {
            type: 'string',
            source: 'html',
            selector: '.gut-hook-text'
        },
    },
    example: {
        attributes: {
            cover: 'https://image.shutterstock.com/image-vector/example-sign-paper-origami-speech-260nw-1164503347.jpg',
        },
    },
    edit: Edit,
    save,
} )

I tried with basics attributes. Same result...

example: {
        attributes: {
            backgroundColor: '#000000',
            textColor: '#FFFFFF',
            title: __( 'I am a test', 'ccn-gut' ),
        },
    },

I Tried with code sample example too :

example: {
    attributes: {
        cover: 'https://image.shutterstock.com/image-vector/example-sign-paper-origami-speech-260nw-1164503347.jpg',
    },
    innerBlocks: [
        {
            name: 'core/paragraph',
            attributes: {
                content: __(
                    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et eros eu felis.'
                ),
            },
        },
    ],
},

I followed this tutorial without any success : https://mediaron.com/how-to-enable-gutenberg-block-previews/

enter image description here

1 Answers

Gutenberg basically just renders your block as you define it in the edit and save functions, so if the image isn't showing up, you likely haven't told Gutenberg where/how you'd like the image to appear.

Looking at the code you provided, it looks like you haven't defined a cover attribute on the ccn/gut-text-title block you are registering. You'll need to add that to the attributes object, e.g.:

attributes: {
  content: {
    type: 'string',
    source: 'html',
    selector: '.gut-hook-text'
  },
  cover: {
    type: 'string',
  },
},

Then, in your edit and save functions you'll need to define how that cover attribute should be displayed, e.g.:

edit: ( { attributes } ) => {
  const {
    cover,
  } = attributes;

  return (
    <img src={ cover }/>
  );
}
Related