0

I am trying to insert some dummy text at the current cursor position in the quill react package. But I get the following error in the console:

quillRef.getSelection is not a function

Here is the code:

import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

  const editorRef = useRef();

  const insertText = (quillRef) => () => {
    var range = quillRef.getSelection();
    console.log("range", range);
    let position = range ? range.index : 0;
    quillRef.insertText(position, "Hello, World! ");
  };

  <Button onClick={insertText(editorRef.current)}>Add Text</Button>


          <ReactQuill
            ref={editorRef}
            name="format"
            id="text-area"
            theme="snow"
            value={values.format}
          />
Moaz Ali
  • 53
  • 5

2 Answers2

1

For getSelection, use the following:

quil.current.getEditor().getSelection();

And for insert text, use the following:

quil.current.getEditor().insertText(position, "Hello, World! ");
Moaz Ali
  • 53
  • 5
0

It looks like the editorRef is not correctly referencing the Quill editor instance. The ref attribute should be passed to the ReactQuill component, not the Button component.

Try the following:

<ReactQuill
  ref={editorRef}
  name="format"
  id="text-area"
  theme="snow"
  value={values.format}
/>
<Button onClick={insertText(editorRef.current)}>Add Text</Button>

Then, in the insertText function, you can use quillRef.getSelection() to get the current selection.

const insertText = (quillRef) => () => {
  var range = quillRef.getSelection();
  console.log("range", range);
  let position = range ? range.index : 0;
  quillRef.insertText(position, "Hello, World! ");
};