Tuesday, 29 October 2019

Dynamically wrap text in an anchor tag in Quilljs Error: addRange(): The given range isn't in document

I'm looking to search the editor text for any hashtags, and wrap the hashtag in an anchor tag to make it a link. So this: #whatsup would be this: <a href='http://help.com'>#whatsup</a>.

Here's what I have so far, which modifies the text correctly but results in this error. addRange(): The given range isn't in document And the cursor is removed, disallowing me to type anything else.

I get the same error when using setContents rather than dangerouslyPasteHTML

Just type any hashtag value such as #foo into the code snippet and look at your console to reproduce the error. Any help much appreciated.

class RichEditor extends React.Component {
    constructor (props) {
        super(props)
        this.state = { 
            editorHtml: '',
            hashTags: [] 
        }
        this.modules = {
            toolbar: [
                [{ header: [1, 2, false] }],
                ['bold', 'italic', 'underline'],
                ['image', 'code-block']
              ]
        }

        this.editor = null;
        this.quillRef = null;
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange (html) {
        var blurtHashtags = this.editor.getText().match(/(?:^|\B)#[a-zA-Z][\w]{1,19}\b/g);

        if (blurtHashtags) {
            var modHtml = html.replace(blurtHashtags[0], "<a href='http://help.com'>" + blurtHashtags[0] + "</a>");
                 this.editor.clipboard.dangerouslyPasteHTML(modHtml);
        } else {
            this.setState(prevState => ({
                editorHtml: html 
            }));
        }
    }
    
    componentDidMount() {
        if (typeof this.quillRef.getEditor !== 'function') return;
        this.editor = this.quillRef.getEditor();
    }
    
    render() {
        return (
            <div>
                <ReactQuill
                    ref={(el) => { this.quillRef = el; }} 
                    onChange={this.handleChange} 
                    modules={this.modules}
                />
            </div>
        );
    }
}

ReactDOM.render( <
  RichEditor / > ,
  document.getElementById("quill")
);
<div id="quill"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/prop-types/prop-types.js"></script>
<script src="https://unpkg.com/react-quill@latest/dist/react-quill.js"></script>
<link href="//cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">


from Dynamically wrap text in an anchor tag in Quilljs Error: addRange(): The given range isn't in document

No comments:

Post a Comment