Using applyFormat (from @wordpress/rich-text) to make persistent changes to Gutenberg’s rich text value

I finally figured it out. Just posting it here if anyone needs to do this as the Gutenberg documentation lacks code examples.

With reference to the below code, blockIndex is the block you are dealing with; and startIndex and endIndex are ranges to annotate in context of the block:

// Get latest modified content of the block
let html = wp.data.select( "core/editor" ).getBlocks()[blockIndex].attributes.content;
// Get uuid of the block
let blockUid = wp.data.select( "core/editor" ).getBlocks()[blockIndex].clientId;
// Create a RichText value from HTML string of block content
let value = wp.richText.create({
  html
});
// Apply a format object to a Rich Text value from the given startIndex to the given endIndex
value = wp.richText.applyFormat(value, { type: 'strong' }, startIndex, endIndex);
// Update the block with new content
wp.data.dispatch( 'core/editor' ).updateBlock( blockUid, {
    attributes: {
      content: wp.richText.toHTMLString({
        value
      })
    }
  } );

Leave a Comment