Implementing Gutenberg RichText onSplit / onReplace

I need an unordered list, but with options selected for each list item. To achieve this I’ve created a custom block called icon-list which is a ul element with InnerBlocks, which allows only my custom icon-list-item block as a child. My icon-list-item block is just a RichText element with tagName: li and some controls. This all works fine, but currently pressing the enter key adds a line break to the current icon-list-item block – what I’d really like is for the enter key to insert a new icon-list-item block. Similarly pressing the backspace key when at the start of a icon-list-item block should remove that block – the exact same functionality of the core/list block.

I’ve had a dig through the Gutenberg docs and source and found that I need to implement the onSplit and onReplace properties for my RichText element, but it’s not clear to me how I actually do this. So far I have:

el(RichText, {
    tagName     : 'li',
    className   : 'icon--' + props.attributes.icon,
    value       : props.attributes.content,
    placeholder : props.attributes.placeholder,
    onChange    : function(value) {
        props.setAttributes({ content: value })
    },
    onSplit     : function(value) {
        if (!value) {
            return createBlock('tutti/icon-list-item');
        }

        return createBlock('tutti/icon-list-item', {
            ...props.attributes,
            content: value,
        }
    },
    onReplace   : function() {
        // something
    }
})

… obviously I’m completely lost when it comes to the onReplace function. Any pointers would be very much appreciated!

1
1

Not tested. I just was browsing looking for something else. But I would try something like this:

onReplace: function() {
   var myID    = props.clientId;
   wp.data.dispatch('core/block-editor').removeBlock(myID);
}

Leave a Comment