How to implement autocomplete plugins to React TypeScript frontend?

52 Views Asked by At

I'm trying to build a custom editor using React TypeScript and CKEditor4, and I've been following this guide here https://ckeditor.com/docs/ckeditor4/latest/features/autocomplete.html but the example provided in here https://ckeditor.com/docs/ckeditor4/latest/features/autocomplete.html is written in html.

I've been trying to replicate it in React with the below code:

function matchCallback(text, offset) {
        var pattern = /\[{2}([A-z]|\])*$/,
            match = text.slice(0, offset)
                .match(pattern);

        if (!match) {
            return null;
        }

        return {
            start: match.index,
            end: offset
        };
    }

    function dataCallback(matchInfo, callback) {
        var data = PLACEHOLDERS.filter(function (item) {
            var itemName = '[[' + item.name + ']]';
            return itemName.indexOf(matchInfo.query.toLowerCase()) == 0;
        });

        callback(data);
    }
    return (
        <CKEditor
        debug={true}
        // editorUrl="https://your-website.example/ckeditor/ckeditor.js"
        initData="<p>Hello from CKEditor 4!</p>"
        name="my-ckeditor"

        onInstanceReady={({ editor }) => {
            var itemTemplate = '<li data-id="{id}">' +
                '<div><strong class="item-title">{title}</strong></div>' +
                '<div><i>{description}</i></div>' +
                '</li>',
                outputTemplate = '[[{title}]]<span>&nbsp;</span>';

            new editor.plugins.autocomplete(editor.editor, {
                textTestCallback: (range)=>{ if (!range.collapsed) {
                    return null;
                }
        
                return editor.plugins.textMatch.match(range, matchCallback);},
                dataCallback: (matchInfo, callback) => {
                    var data = PLACEHOLDERS.filter(function (item) {
                        var itemName = '[[' + item.name + ']]';
                        return itemName.indexOf(matchInfo.query.toLowerCase()) == 0;
                    });
            
                    callback(data);
                },
                itemTemplate: itemTemplate,
                outputTemplate: outputTemplate
            });

            
        }}
        onFocus={({ editor }) => {
            // Handles native `focus` event.
        }}

        readOnly={false}
        style={{ borderColor: 'blue' }}
        type="classic"
    />

But I'm getting this error:

TypeError: editor.plugins.autocomplete is not a constructor

So what did I do wrong here? How to correctly implement the autocomplete plugin to React TypeScript?

0

There are 0 best solutions below