I have a component wrapper in antd
Form.create()
HOC where I want to implement validation for my react-quill
editor.
<Form.Item>
{getFieldDecorator('input', {
rules: [RequiredRule],
initialValue: text,
onChange: this.onChangeText
})(
<ReactQuill
className="question-form__rich-text"
modules={quillToolbar}
/>,
)}
</Form.Item>
If I start typing inside my quill
editor text field it triggers the onChangeText
function which in its turn changes the local state and initiates rerender of the component
onChangeText = (_, __, ___, editor) => {
this.setState({
textVal: editor.getText(),
});
};
this.state = {
textVal: '',
};
Every time the component rerenders my text field loses focus, so I have to click inside the field to type another letter.
I noticed that it happens only if the <ReactQuill>
component is wrapped by antd
<Form.Item>
It also shows some weird behaviour if I put console.log
inside onChangeText
function and try to check what's inside the text field:
Let's say my text field is initially empty. I type letter 'a' and it calls the function 3 times. First, it shows that the text field contains letter 'a', then it calls the function again showing that the field is empty and then the 3rd time letter 'a' appears again. This behaviour persists as I keep typing.
Also, there is an warning saying addRange(): The given range isn't in document.
which I have no idea what it means.
I've been struggling with that issue for a few days now, any help would be greatly appreciated. Thank you
The reason it's loses focus when keypress is probably because the quill component is recreating when rerendering. See this same question about losing focus when typing.
I can't find a sample of implementing react quill on antd using getFieldDecorator
, so I made a little workaround to make it work but same output. See this working link I made.
const { getFieldDecorator, validateFields, setFieldsValue } = props.form;
const onChangeText = (text) => {
console.log("called");
text = text !== "<p><br></p>" ? text : "";
setFieldsValue({ input: text });
setTextVal(text);
};
<Form.Item>
{getFieldDecorator("input", {
rules: [{ required: true }],
})(<Input.TextArea style={{ display: "none" }} />)}
<ReactQuill
className="question-form__rich-text"
modules={quillToolbar}
defaultValue={textVal}
onChange={onChangeText}
/>
</Form.Item>
as you can see in the above code, I place the editor outside getFieldDecorator
and replaced it with hidden <Input>
so your set of rules will still applied. The quill component is uncontrolled component and every time it change, it will also change the value of the hidden <Input>
so when you submit or get the value of the form, the value of it is the value of quill component.
Also the warning you get addRange(): the given range isn't in the document
was not visible on the codesandbox. You may look into this about that.