Search code examples
javascriptwordpressgutenberg-blocks

Java Script / Wordpress Gutenberg Block Plugin / cant add a second class to div


Maybe someone can help me with this strange behavior ...

I am writing on a "Wordpress Gutenberg Block" plugin and just want to give the first div a second class in the return function.

It works but not then it should.

I want get:

<div class="wp-block-womoblocks-katblock col-lg-4">

But i get always:

<div class="wp-block-womoblocks-katblock undefinedcol-lg-4">

Here is the code of the function:

save: function( props ) {

    var attributes = props.attributes;
    var colg4 = "col-lg-4";
    var colclass = props.className + colg4;
    return (
        el( 'div', { className: colclass },
        el( 'div', { className: 'col-lg-4' },
        el( 'div', { className: 'kat-post' },

        el( RichText.Content, {
            tagName: 'h2', value: attributes.title
        } ),
        attributes.mediaURL &&
            el( 'div', { className: 'kat-image' },
                el( 'img', { src: attributes.mediaURL } ),
            ),
            el( RichText.Content, {
                tagName: 'div', className: 'kat-ausz', value: attributes.instructions
            } ),
        )))
    );
},

I have tried several options but I always get this undefined before col-lg-4 and have no ideas on how to solve it.

Thank you very much!


Solution

  • The problem is in the assignment of colclass because there is no need for props.className.

    In save function of registerBlockType class is added automatically to the outermost element but in edit function you have to explicitly write it so mistakenly you are using same approach on both.

    I also suggest you to use the more latest ES6 / ESNext syntax instead of ES5 because it's friendly to code in that, Gutenberg docs also have a toggle that shows you ESNext code.