WordPress: Embed code with custom Gutenberg block

1k Views Asked by At

I am trying to include a Custom HTML embed input on my Gutenberg block but can't figure out how to do it.

I was wondering what is the best way to add HTML inside a block the same way that you do it with the Custom HTML block. Is there a Gutenberg element I missed?

I tried the approach of

attributes:{
        embed: {
            type: 'string',
            default: null,
        },
        ....
        }

Then I created a RichText on edit()

   let {  embed, ..... } = attributes;

<label>Embed HTML code here</label>
                    <RichText
                        tagName="div"
                        className="rich-text-holder"
                        placeholder= "Add the HTML"
                        value={ embed }
                        onChange={ ( embed ) => setAttributes( { embed } ) }
                    />

and finaly again on save()

let { embed, .... } = attributes;

        function createMarkup() {
            return {__html: { embed } };
          }

 return().....
                    { embed &&
                    //<RawHTML className="listing-embed" >{ embed }</RawHTML>
                    <div dangerouslySetInnerHTML={ createMarkup() } />
                    }
....

My first problem is that the attribute is saved as &lt;iframe src="https://www.w3schools.com">&lt;/iframe> for example. The second problem is that on frontend I see just an empty div.

The third problem is that even if I manage to make the code appear it appears as text and not as actual code in the frontend

Do you have any better approach or know what is wrong with my code?

1

There are 1 best solutions below

1
On BEST ANSWER

You can view how the Custom HTML block does it in the github repository for Gutenberg.

My first problem is that the attribute is saved as <iframe src="https://www.w3schools.com"></iframe> for example.

Presumably this is because you are using RichText. Could you use a TextareaControl instead and perhaps it won't escape the content?

The second problem is that on frontend I see just an empty div.

I imagine this is because the HTML is invalid