Gutenberg Custom RegisterFormatType with PlainText in InspectorControl

Here is what I am trying to achieve.

Register a new Format Type e.g. tooltip.
Show the tooltip option in the toolbar.
If a user adds a paragraph block and types a few words, by selecting a word we can add tooltip by choosing from the toolbar.
In the sidebar, I need to show a plain text field to be able to add the tooltip title.
We can add multiple tooltips by selecting the words and we should be able to enter different titles for those tooltips.

How can I achieve this? Here is my code.

import { InspectorControls, PlainText } from ‘@wordpress/editor’;
import { Component } from ‘react’;

const { registerFormatType, toggleFormat } = wp.richText;
const { RichTextToolbarButton } = wp.blockEditor;

class MyTooltip extends Component {
constructor(props) {
super(props);
}

render() {
const { isActive, value, onChange } = this.props;
const type = ‘my-custom-format/tooltip’;

return (
<div>
{isActive && (
<InspectorControls key=”inspector”>
<PlainText
value=””
onChange=””
/>
</InspectorControls>
)}

<RichTextToolbarButton
icon=”editor-code”
title=”Tooltip”
isActive={isActive}
onClick={() => {
onChange(
toggleFormat(value, {
type: type,
attributes: {
title: theTitle
}
})
);
}}
/>
</div>
);
}
}

registerFormatType(‘my-custom-format/tooltip’, {
title: ‘Tooltip’,
tagName: ‘span’,
attributes: {
title: ‘title’
},
className: ‘tooltip-wrapper’,
edit: MyTooltip
});

I want to know how I can maintain different variables for the component in the InspectorControl since I can have multiple tooltips in the same paragraph.

e.g.: This is a paragraph with tooltip1 and also tooltip2

Here the tooltip1 and tooltip2 can have different titles in which users can enter using the InspectorControl in the sidebar.

Read more here:: Gutenberg Custom RegisterFormatType with PlainText in InspectorControl

Leave a Reply

Your email address will not be published. Required fields are marked *