WordPress Blocks: Hydrate InnerBlocks From HTML

— by

Quick tip about creating or replacing InnerBlocks from HTML in the WordPress block editor. For instance if your block pulls information from a remote API and you want to display as part of the post, or embed in the post such that it’s editable. The block editor (gutenberg) already handles the job very simply.

Use pasteHandler. It not only includes HTML support, but plain text & markdown also!

import { pasteHandler } from '@wordpress/blocks';

And from a dispatch of the block-editor store, use the replaceInnerBlocks() method.

I had a couple issues with the code that made it somewhat confusing.

  1. I’m still getting used to the concept of React hooks, so managing the useSelect, useDispatch, and useCallback might not be 100% correct — but this incantation worked for me 😆.
  2. Originally I tried updating the first InnerBlock and finding it was slightly tricky. Good news — this is actually fairly simple with useSelect to getBlocksByClientId() and then just get the innerBlocks property of the first block returned.

InnerBlocks Example:

// `clientId` is passed as a prop to the edit component.
const { replaceInnerBlocks } = useDispatch( 'core/block-editor' );

// call `updateInnerBlocks( markdownOrHTMLContent );`
const updateInnerBlocks = useCallback(
	source => {
		// Get an array of inner blocks
		const newInnerBlocks = pasteHandler( {
			HTML: '',
			mode: 'BLOCKS',
			plainText: source,
		} );
		replaceInnerBlocks( clientId, newInnerBlocks );
	},
	[ innerBlocks ]
);

Interested in more? See other posts about WordPress and the block editor.

Newsletter

Our latest updates in your e-mail.

%d bloggers like this: