简体   繁体   中英

use formik on react-draft-wysiwyg

I am using formik for my forms. I wanted to implement react-draft-wysiwyg editor with formik. However, I found following warning in my case.

Warning: Formik called `handleBlur`, but you forgot to pass an `id` or `name` attribute to your input:

Because of which I think, I cannot show error if it has validation issue and also the state is not preserved if i move to next form and come back to the form where I have put content on the editor.

Is that the warning responsible for those issues or I have missed something important?

Here is how I am trying to bind formik with 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``;

When rendering the form I am doing the follow

<Field
    component={EditorField}
    name="article"
    label="Write an article"
    placeholder="content here"
/>

The data I get from server is shown on the editor though.

in The component Editor.js

import { useField } from "formik";
const [field, meta] = useField(props.name);
const error = meta.touched && meta.error;

I added bellow <Editor ... />

{meta.touched && meta.error && (
  <FormHelperText>{error}</FormHelperText>
)}

In the page where I used the Editor when click in the editor , the value will be by default <p></p> and length 8 so the test of dirty ll be true

<EditorDraft
  name="value"
  style={{ maxHeight: "200px" }}
  // when click in the editor , the value will be by default <p></p> and length 8
  handleChange={(v) => {
    if (v.length > 8) {
      setFieldValue("value", v);
    } else {
      setFieldValue("value", "");
    }
  }}
  defaultValue={values.value}
  toolbar={{
    options: [
      "inline",
      "blockType",
      "fontSize",
      "fontFamily",
      "list",
      "textAlign",
      "colorPicker",
      "remove",
      "history",
    ],
  }}
/>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM