zenoamaro / react-quill

A Quill component for React.
https://zenoamaro.github.io/react-quill
MIT License
6.71k stars 914 forks source link

React-Quill cursor position set using function #668

Open shreedharan opened 3 years ago

shreedharan commented 3 years ago

I have a issue in react-quill setEditorSelection I am able to get the editor cursor position but I am not able to set the cursor to specific position can you help me Here is my code import React, {Component} from 'react'; import ReactQuill from 'react-quill' import "react-quill/dist/quill.snow.css"; import './App.css';

class App extends Component{ constructor(props) { super(props); this.state = { editorHtml: "testing" }; this.handleChange = this.handleChange.bind(this); this.handleChangeSelection = this.handleChangeSelection.bind(this);

this.reactQuillRef = null

}

handleChange(content, delta, source, editor) { console.log(content); console.log(delta); console.log(source); console.log(editor.getSelection()); //console.log("IBM"+editor.getHTML()); // HTML/rich text //alert(event); //this.setState({ editorHtml: editor.getHt }); }

handleChangeSelection(e) { console.log(e); }

moveCursor = () => { this.reactQuillRef.focus();

console.log(this.reactQuillRef.getEditorSelection().index);
//console.log(this.reactQuillRef);

var range = this.reactQuillRef.getEditorSelection().index;

}

render(){ return (

{ this.reactQuillRef = el }} autoFocus="true" onChange={this.handleChange} onChangeSelection={this.handleChangeSelection} value={this.state.editorHtml} theme={"snow"} // pass false to use minimal theme />
);

} }

export default App;

Sanan4li commented 3 months ago

Sad to see that it's been 4 years and no reply to this issue.

ht-la commented 5 days ago

I also encountered the same problem, when ReactQuill render, I want the cursor position to automatically focus on the last position of the value. I solved the problem by the following way:

  useEffect(() => {
    if (!quillRef.current) return;

    setTimeout(() => {
      quillRef.current?.editor?.setSelection(
        quillRef.current.editor?.getLength() || 0,
        0,
      );
    }, 0);
  }, [quillRef]);

I tested, if there is no setTimeout, it will only focus on the first position. Hope this way can help you.