Search code examples
wordpress-gutenberggutenberg-blocks

How to provide class with multiline element gutenberg RichText block?


I'm using following code for gutenberg RichText block

el(
    RichText,
    {
        key: 'editable',
        tagName: 'ul',
        multiline: 'li',
        className: 'list-group',
        onChange: onChangeContent,
        value: content,
    }
)

Can anyone help me how to assign a class list-item with multiline li element?


Solution

  • I don't think gutenberg supports this out of the box. You can modify the content of the rich text editor by replacing the <li> with <li class="list-item"> in the save function. You need to make use of dangerouslySetInnerHTML to render string as html inside <ul>

    save: function save(props) {
        function createMarkup() {
            return { __html: props.attributes.content.replace(/<li>/g, '<li class="list-item">') };
        }
    
        return el('ul', { dangerouslySetInnerHTML: createMarkup() });
    }
    

    UPDATED If you need to do this immediately when you add a new <li> in the editor itself, then you need to call a function to add the class to the <li> elements in the onChange event of the RichText component.

    edit: function edit(props) {
        function setCustomClass() {
            $('.list-group li').addClass('list-item');
        }
        return el(RichText, {
            key: 'editable',
            tagName: 'ul',
            multiline: 'li',
            className: 'list-group',
            onChange: function onChangeContent(content) {
                props.setAttributes({ content: content });
                setCustomClass();
            },
            value: props.attributes.content
        });
    },