How to Create Custom Text Formats for Gutenberg Block Editor

How to Create Custom Text Formats for Gutenberg Block Editor

A few days ago, I published Extending Gutenberg Core Blocks with Custom Attributes and Controls. Well, now I’m going to help you create custom rich text formatting for Gutenberg blocks using registerFormatType function.

As of version 1.4.3,  underline format is available on EditorsKit plugin. In this tutorial I’ll show you how I created this new rich text format. 

Registering a new format

Let’s start with the registerFormatType function available on Rich Text API. This function gives ability to register custom format with unique name and object to define its behavior. It accepts the following parameters:

  • name string: Format name.
  • settings Object: Format settings.
  • settings.tagName string: The HTML tag this format will wrap the selection with.
  • settings.className [string]: A class to match the format.
  • settings.title string: Name of the format.
  • settings.edit Function: Should return a component for the user to interact with the new registered format.

registerFormatType function returns :

(WPFormat|undefined): The format, if it has been successfully registered; otherwise undefined.

Create Custom Underline Text Format

Now that we understand how the function works and the parameters, we can start creating our Underline text format.

To give another emphasis, name should be unique in order to prevent conflicts which will cause an error on the editor. I’ll be using editorskit/underline for this tutorial. 

Create Custom Underline Text Format

The code above will wrap the selected text with <span> that I’ve added as parameter value for tagName. When format is toggled on it will also add text-decoration: underline; as style attribute.

That’s it, actually. It’s pretty simple once you’ve gotten used to it. You can also use className if you don’t want to add inline styling and use class instead. Then change the onToggle function to const onToggle = () => onChange( toggleFormat( value, { type: name } ) );

Whichever methods you prefer is really up to you, either works perfectly.

How to Create Custom Text Formats for Gutenberg Block Editor

Wrapping Up 

That’s all for my another post-Gutenberg tutorial. I hope this will help filling the gaps when it comes to development tutorials. Make sure to subscribe and follow me on Twitter to check the latest articles. If you need any help with Gutenberg coding, just let me know on the comment section below and I’ll decide which topic I’ll write next.

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Extending Gutenberg Core Blocks with Custom Attributes and Controls

Extending Gutenberg Core Blocks with Custom Attributes and Controls