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.
- I’m still getting used to the concept of React hooks, so managing the
useSelect
,useDispatch
, anduseCallback
might not be 100% correct — but this incantation worked for me 😆. - Originally I tried updating the first
InnerBlock
and finding it was slightly tricky. Good news — this is actually fairly simple withuseSelect
togetBlocksByClientId()
and then just get theinnerBlocks
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.