How to Add a Button to The Gutenberg Editor
Since the documentation is still quite poor (as I write this post), I’m going to explain how to add a custom button to the text blocks of the block editor, so you don’t waste your time and have an easier time than me.
You’ll find all the plugin code that adds a button to the editor in this GitHub repository. Although it’s quite simple, I’m going to explain in more detail the most important parts of this project.
The
<span>registerFormatType</span>
function is specific to the WordPress core and is the one that allows you to add a new format type, together with the button that triggers the action. You pass a name (<span>'nelio/button'</span>
) and a JavaScript object with arguments as parameters. Among those arguments, you have the<span>edit</span>
method, which is the one that returns a React Element, which in our case will be the button we want to put in the block.This button is a RichTextToolbarButton, which is nothing more than a React component of the Gutenberg editor itself that you can find defined here. This component needs an icon (which is an SVG file with Nelio’s logo, in this case), the title of the button, and a function that will be executed when the button is clicked. This function ends up calling the doTheJob function, where the selected text is retrieved and printed in the browser’s console. That’s the place where you can add any JavaScript code you want to handle that selected text.
In the icon attribute of RichTextToolbarButton you can put a string with the name of a WordPress Dashicon instead of the SVG. For the SVG to work, keep in mind that we use the svg-react-loader package that converts SVG files into React elements, which is what this React components need.