Rameez Iqbal
Rameez Iqbal

Reputation: 507

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?

Upvotes: 4

Views: 2182

Answers (1)

Swopnil Dangol
Swopnil Dangol

Reputation: 664

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
    });
},

Upvotes: 1

Related Questions