0
votes

As shown in the code snippet below, I am trying to append HTML or JSX to RichText content in vain.

const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;

registerBlockType( /* ... */, {
    // ...

    attributes: {
        content: {
            type: 'array',
            source: 'children',
            selector: 'p',
            default: [],
        },
    },

    edit( { className, attributes, setAttributes } ) {

        const updateContentWithString = ( content ) => {

            setAttributes( { content: content.concat( 'test' ) } );

        }

        const updateContentWithHTML = ( content ) => {

            setAttributes( { content: content.concat( <Button isDefault >Test Button</Button> ) } );

        }

        return (
            <RichText
                tagName="p"
                className={ className }
                value={ attributes.content }
                onChange={ updateContentWithString } // updateContentWithString works fine BUT updateContentWithHTML doesn't work at all
            />
        );
    },

    save( { attributes } ) {
        return <RichText.Content tagName="p" value={ attributes.content } />;
    }
} );

I am wondering why updateContentWithString() works fine BUT updateContentWithHTML() doesn't work at all.

Kindly guide me on this.

Thanks

1

1 Answers

0
votes

Try

setAttributes( { content: content.concat( '<Button isDefault >Test Button</Button> )' } );

In JSX <Button/> will be preprocessed/conversed to React.createElement to create component.

Note: In JSX <Button/> differs from <button/> (component vs. html)

UPDATE:

Above was related to react/JSX only. I don't know or used Gutenberg (yet) but according to this html elements should be passed as objects, not html source. Probably you should use wp.element.createElement or RichText or even define/use own custom block types.

Search for method of editing/updating/creating html (elements) in Gutenberg.