0
votes

Here is my step by step scenario:

  1. Create several posts using Gutenberg which can include any type of blocks/elements
  2. Create a page using Gutenberg
  3. Create a custom widget (called load-post-widget) in Gutenberg which on load will fetch a post content from existing posts display in the page.
  4. The load-post-widget upload loading the post content SHOULD be editable just like any other post content using Gutenberg editor mode.

However, i am unable to edit the fetched post content using the 'load-post-widget', I guess i am not sure how to return the post content so that Gutenberg treats it as an editable form. Kindly help.

Qn: How do i render any post.content.raw as a react Element which can be editable using Gutenberg.

Here is the sample code as in step 3:

registerBlockType( 'test/load-post-widget', {
    title: 'Load Post Widget',
    icon: 'smiley',
    category: 'widgets',

    edit: withSelect((select) => {
            return {  posts: select('core').getEntityRecords('postType', 'post')};
        })(({ posts, className }) => {
        if ( ! posts ) {
            return 'Loading...';
        }
        if ( posts && posts.length === 0 ) {
            return 'No posts';
        }
        let post = posts[0]; // hard coded as of now.

        // Option 1: This does not make the rendered post content/blocks editable
        return <div dangerouslySetInnerHTML={ { __html: post.content.raw } }></div> 
    } ),
} );
1

1 Answers

0
votes

Easy, but took ages to figure it out! (its hidden in thousands of API docs in wp)

import {
    registerBlockType,
    parse,
    parseWithAttributeSchema,
    pasteHandler,
    rawHandler
} from '@wordpress/blocks';

apiFetch({ path: 'wp/v2/posts/${offerId}' }).then(postResponse => {
                console.log(' POSTS LIST :: ', postResponse);
                const htmlStr = postResponse.content.rendered;
                const blocks = pasteHandler({ plainText: htmlStr,  mode: 'AUTO', canUserUseUnfilteredHTML: true });
                wp.data.dispatch('core/editor').insertBlocks(blocks, 1, self.props.clientId);
            });