Is there any easier way to make ref to editor?
bologer opened this issue · 3 comments
I am wondering if this example from here is the only way to make ref to editor:
class Editor extends React.Component {
constructor(props) {
super(props)
this.quillRef = null; // Quill instance
this.reactQuillRef = null; // ReactQuill component
}
componentDidMount() {
this.attachQuillRefs()
}
componentDidUpdate() {
this.attachQuillRefs()
}
attachQuillRefs = () => {
if (typeof this.reactQuillRef.getEditor !== 'function') return;
this.quillRef = this.reactQuillRef.getEditor();
}
insertText = () => {
var range = this.quillRef.getSelection();
let position = range ? range.index : 0;
this.quillRef.insertText(position, 'Hello, World! ')
}
render() {
return (
<div>
<ReactQuill
ref={(el) => { this.reactQuillRef = el }}
theme={'snow'} />
<button onClick={this.insertText}>Insert Text</button>
</div>
)
}
}
What If I have nested components:
<Component/>
this.editorRef = null;
...
<ComponentChild/>
<ComponentEditor ref={editorRef}/>
Does this mean that I will need to pass callback (e.g. attachQuillRefs
) to the ComponentEditor
to set ref on Component
when ComponentEditor
was mounted?
What I am trying to do is to use focus()
, etc on editor.
Thanks.
Create a ref with React.createRef(), and you can pass that down to your components via their props. Will be populated on mount in those components
The new createRef API (thanks @jamiehill) would simplify the React part a little bit but you're basically waiting on both React and Quill to initialize. It's a bit verbose, but that's because of null checking when accessing the ref before the editor is created.
@alexkrolick thank you that was enlightening.