How to Add a Button to The Gutenberg Editor

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 key project file is the one you will find at /src/js/gutenberg.js and that you have below:

import ElementIcon from ../images/logo.svg;
const { Fragment } = wp.element;
const { __ } = window.wp.i18n;
const { registerFormatType, unregisterFormatType } = window.wp.richText;
const { RichTextToolbarButton } = window.wp.editor;
unregisterFormatType( nelio/button );
registerFormatType( nelio/button, {
  title: __( Nelio, nelio-content ),
  tagName: span,
  className: null,
  edit({ value }) {
    const onClick = () => doTheJob( value );
    return (
      <Fragment>
        <RichTextToolbarButton
          icon={ <ElementIcon /> }
          title={ __( Nelio, nelio-content ) }
          onClick={ onClick }
      />
      </Fragment>
    );
  }
});
function doTheJob( value ) {
  let selectedText = value.text.substring( value.start, value.end );
  if ( 0 === selectedText.length ) {
    return;
  }//end if
  // Do things with the selected text here…
  console.log( selectedText );
}//end openDialogToCreateAMessage()
view rawgutenberg.js hosted with ❤ by GitHub