Я использую formik
для своих форм. Я хотел реализовать react-draft-wysiwyg
редактор с formik. Тем не менее, я обнаружил следующее предупреждение в моем случае.
Warning: Formik called `handleBlur`, but you forgot to pass an `id` or `name` attribute to your input:
Из-за которого, я думаю, я не могу показать ошибку, если она имеет проблему проверки, а также состояние не сохраняется, если я перехожу к следующей форме и возвращаюсь в форму, где я положил содержание в редакторе.
Это предупреждение отвечает за эти проблемы, или я пропустил что-то важное?
Вот как я пытаюсь связать formik
с react-draft-wysiwyg
import React from "react";
import styled from "styled-components";
import { Editor } from "react-draft-wysiwyg";
import htmlToDraft from "html-to-draftjs";
import draftToHtml from "draftjs-to-html";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const EditorField = ({
input,
meta,
field,
form,
label,
placeholder,
labelCss
}) => {
const [active, setActive] = React.useState();
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
React.useEffect(() => {
if (form.dirty) {
return;
}
if (!field.value) {
return;
}
const contentBlock = htmlToDraft(field.value);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
}
}, [field.value, form.dirty]);
const onEditorStateChange = editorState => {
changeValue(editorState);
};
const changeValue = editorState => {
setEditorState(editorState);
form.setFieldValue(
field.name,
draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
};
const hasError = form.touched[field.name] && form.errors[field.name];
return (
<>
<Wrapper>
{label && (
<Label isActive={active} css={labelCss}>
{label}
</Label>
)}
<Editor
editorState={editorState}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
onEditorStateChange={editorState => onEditorStateChange(editorState)}
placeholder={placeholder}
toolbar={{
options: [
"inline",
"blockType",
"fontSize",
"fontFamily",
"list",
"textAlign",
"link",
"embedded",
"remove",
"history"
]
}}
name={field.name}
id={field.name}
onFocus={() => setActive(true)}
onBlur={e => {
setActive(false);
field.onBlur(e);
}}
/>
{!!hasError && <Error>{hasError}</Error>}
</Wrapper>
</>
);
};
export default EditorField;
const Wrapper = styled.div``;
При обработке формы я делаю следующее
<Field
component={EditorField}
name="article"
label="Write an article"
placeholder="content here"
/>
Данные, которые я получаю с сервера, отображаются в редакторе.