Moaz Ali
Moaz Ali

Reputation: 53

quillRef.getSelection is not a function

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}
          />

Upvotes: 0

Views: 2831

Answers (2)

Amrit Maan
Amrit Maan

Reputation: 1

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! ");
};

Upvotes: 0

Moaz Ali
Moaz Ali

Reputation: 53

For getSelection, use the following:

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

And for insert text, use the following:

quil.current.getEditor().insertText(position, "Hello, World! ");

Upvotes: 1

Related Questions