Gutenberg add extra attributes to custom format

I'm creating a custom format (adding a custom option to the format toolbar) using the following guide: https://developer.wordpress.org/block-editor/how-to-guides/format-api/

import { registerFormatType, toggleFormat } from '@wordpress/rich-text';
import { RichTextToolbarButton } from '@wordpress/block-editor';
 
const MyCustomButton = ( { isActive, onChange, value } ) = {
    return (
        RichTextToolbarButton
            icon=editor-code
            title=Sample output
            onClick={ () = {
                onChange(
                    toggleFormat( value, {
                        type: 'my-custom-format/sample-output',
                    } )
                );
            } }
            isActive={ isActive }
        /
    );
};
 
registerFormatType( 'my-custom-format/sample-output', {
    title: 'Sample output',
    tagName: 'samp',
    className: null,
    edit: MyCustomButton,
} );

This creates, for example: Hello sampworld/samp

How can i add extra attributes to the new format? For example if i want to add a data attribute. I tried:

registerFormatType( 'my-custom-format/sample-output', {
    title: 'Sample output',
    tagName: 'samp',
    className: null,
    'data-custom': 'Some value',
    edit: MyCustomButton,
} );

But data-custom does not show in the HTML output.

Topic block-editor Wordpress javascript

Category Web


I was able to add the attribute by passing it in attributes through the registerFormatType settings:

attributes: {
   'custom-attr': 'custom-attr'
},

then in edit():

toggleFormat( value, {
    attributes: {
      'custom-attr': 'Hello world'
    },
} )

I don't know how exactly it all works together because I could not find detailed explanations in the current documentation.

Another great feature would be the ability to add extra HTML markup in custom formats but I could not find any examples. For example:

<div custom-attr="Hello world"><div class="an-extra-div"></div>Lorem ipsum dolor...</div>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.