I am trying to make custom Gutenberg Blocks through a plugin. Everything is going smooth the only issue is when I select my block from the blocks menu, it just pastes the JSON on the front. What I rather want is to render this JSON to make blocks.
I am fetching blocks’ content from an API. I am attaching my code as well.
function makeBlock(block, category){
var jsonBlock = {
"__file": "wp_export",
"version": 2,
"content": ""}
;
$.ajax({
type: "POST",
url: document.location.origin+"/blocknets/wp-admin/admin-ajax.php",
data: {
'action': 'makeBlocks',
'id': block.id
},
dataType: "json",
encode: true,
}).done(function (resp) {
// console.log(resp);
jsonBlock.content = resp.data.content;
});
( function ( blocks, element, data, blockEditor ) {
var el = element.createElement,
registerBlockType = blocks.registerBlockType,
useSelect = data.useSelect,
useBlockProps = blockEditor.useBlockProps;
// debugger;
registerBlockType( 'custom-blocks/'+category+'-'+block.id, {
apiVersion: 2,
title: block.name,
icon: 'megaphone',
category: category,
edit: ()=>{return jsonBlock.content},
save: () => null
} );
} )(
window.wp.blocks,
window.wp.element,
window.wp.data,
window.wp.blockEditor
);
}
Purple Highlighted is my plugin, and Yellow is what it prints out.
What I rather want is to render this JSON. If I just paste this JSON into code editor it would look like this.
Can anyone help me out?
2
Answers
I was able to render all the blocks by using the following edit function:
The
jsonBlock.content
displayed in the Editor view is serialized block content. The first step is to use parse() to transform the content into valid blocks. Next, to render the blocks I found RawHTML can be used to render innerHTML from the block content. The<RawHTML/>
component uses dangerouslySetInnerHTML as seen commonly in React to render inner HTML content. Eg:Edit()
Nb. The example covers parsing and displaying block content in the Editor, it does not cover saving the content, as your existing save() function is set to null.