2
votes

I have started using Gutenberg custom blocks, and I have built custom blocks successfully!

But I have an issue, I need to see the preview of the block when I am not editing it on the Admin side, I don't think Gutenberg provides it, because I searched the documentation, searched the internet but nothing found regarding preview of the block when not in edit state.

I have used Block Lab Plugin and it do have a preview, if Gutenberg don't provide it, how can I have a preview? Any Trick or Hack?

This is my block.js:

(function(blocks, components, element) {
    var el = element.createElement;
    var registerBlockType = blocks.registerBlockType;
    var TextControl = components.TextControl;

    registerBlockType("blocks/test-block", {
      title: "Test Block",
      description: "A custom block.",
      icon: "businessman",
      category: "common",
      attributes: {
        headline: {
          type: "string"
        }
      },

      edit: function(props) {
        var headline = props.attributes.headline;
        var onHeadlineChange = function(val) {
          props.setAttributes({
            headline: val
          });
        };

        return el(TextControl, {
          value: headline,
          label: "Headline",
          onChange: onHeadlineChange
        });
      },
      save: function(props) {
        return el(
          "h3",
          {
            className: "headline"
          },
          props.attributes.headline
        );
      }
    });
  })(window.wp.blocks, window.wp.components, window.wp.element);
1

1 Answers

1
votes

To display your custom block with a preview, just add example: () => {}, to section, in the same way as save and edit. https://prnt.sc/rov8qo

//Custom Gutenberg block
(function(components, element) {
    //Default
    const { registerBlockType } = wp.blocks;

    //Block registration
    registerBlockType('', {
        title: '',
        description: '',
        icon: '',
        category: '',
        keywords: [''],
        attributes: {},

        //Example function
        example: () => {}, //Add this to get block preview works

        //Edit function
        edit: props => {},

        //Save function
        save: props => {}
    });
})(window.wp.components, window.wp.element);

UPDATE 1

In order to make a preview of the block (how it will appear in the front), you need to add styles to this block, the same as on the front, and track props.isSelected this block in editor. Depending on whether the block is selected or not, show different content. enter image description here

//Custom Gutenberg block 
(function(blocks, element, blockEditor) {
    //Default variable
    const { registerBlockType } = blocks;
    const { createElement: el } = element;
    const { RichText } = blockEditor;

    //Block registration
    registerBlockType("blocks/test-block", {
        title: 'Test Block',
        description: 'A custom block.',
        icon: 'businessman',
        category: 'common',
        attributes: {
            title: {
                type: 'string',
                source: 'html',
                selector: '.headline'
            }
        },

        //Example function
        example: () => {},

        //Edit function
        edit: props => {
            const attributes = props.attributes;

            return (
                el( 'div', { className: props.className },
                    //View input field
                    props.isSelected && el(RichText, {
                        tagName: 'h3',
                        placeholder: 'Headline...',
                        keepPlaceholderOnFocus: true,
                        value: attributes.title,
                        allowedFormats: [],
                        onChange: title => props.setAttributes({ title })
                    }),
                    //View frontend preview
                    !props.isSelected && el( 'div', { className: 'block__headline' },
                        el( 'div', { className: 'block__headline-title' }, attributes.title ? attributes.title : 'Entry headline...')
                    )
                )
            );
        },

        //Save function
        save: props => {
            return el( RichText.Content, {
                tagName: 'h3',
                className: 'headline',
                value: props.attributes.title
            });
        }
    });
})(window.wp.blocks, window.wp.element, window.wp.blockEditor);

Css the same as on your frontend.

.block__headline {
    padding: 20px 15px 30px;
    background: #fafafa;
    text-align: center;
}
.block__headline-title {
    font-family: 'Montserrat';
    font-size: 30px;
    font-weight: bold;
    position: relative;
}
.block__headline-title:after {
    content: '';
    display: block;
    width: 40px;
    height: 2px;
    background: #333;
    margin: 0 auto;
}