Shamoon
Shamoon

Reputation: 43559

Unable to access quill instance within a module function

I have:

    const formats = ['header', 'bold', 'italic', 'underline', 'list', 'prediction', 'accepted', 'mention'];
    const modules = {
        mention: {
            allowedChars: /^[a-zA-Z0-9_]*$/,
            mentionDenotationChars: ['@'],
            showDenotationChar: false,
            spaceAfterInsert: false,
            onSelect: (item, insertItem) => {
                clearDocumentState(0)
                const cursorPos = quill.getSelection()
                console.log({ cursorPos })
                insertItem(item)
            },
            source: () => { }
        },
        toolbar: [
            ['bold', 'italic', 'underline'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ header: [1, 2, false] }],
            ['clean']
        ]
    };

    const { quill, quillRef, Quill } = useQuill({
        formats,
        modules,
        placeholder: 'Start writing something amazing...'
    });

I'm using https://github.com/afry/quill-mention and https://github.com/gtgalone/react-quilljs if it matters.

When I try to access the quill instance in the onSelect function, I get:

TypeError: Cannot read property 'getSelection' of undefined

I assume somehow the function is cached and quill isn't defined yet. Any way to get that instance?

Upvotes: 5

Views: 2007

Answers (1)

lissettdm
lissettdm

Reputation: 13078

You can set the onSelect callback in useEffect block when quill has value. Use getModule to get the mention module and set the corresponding option:

 React.useEffect(() => {
    if (quill) {
      quill.getModule('mention').options.onSelect = ((item, insertItem) => {
        clearDocumentState(0);
        const cursorPos = quill.getSelection();
        console.log({ cursorPos });
        insertItem(item);
      });
    }
  }, [quill]);

Working example

Upvotes: 2

Related Questions