Can we use wysiwyg editor with antd form?

569 views Asked by At

I have to use react-draft-wysiwyg which is an editor and previously I was handling it via react states. Now, I was thinking if there is a way to use it with antd form. Here is my code,

import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { Form, Button } from "antd";

export default function App() {
  const [form] = Form.useForm();

  return (
    <Form onFinish={(values) => console.log(values)}>
      <Form.Item name="editor">
        <Editor
          onEditorStateChange={(value) =>
            form.setFieldsValue({ editor: value })
          }
          toolbarClassName="toolbarClassName"
          wrapperClassName="wrapperClassName"
          editorClassName="editorClassName"
          style={{ border: "1px solid black" }}
        />
      </Form.Item>
      <Button htmlType="submit">Submit</Button>
    </Form>
  );
}

Antd is not automatically handling editor state rather I have to manage it dynamically, which will work fine in this case but I was wondering if there is a way to capture the editor values directly in form without handling it dynamically. As, antd is not compatible with react-draft-wysiwyg and it prefers using react-quill but I still want to use it.

What I have done is, handled the value by myself and storing it in the form and according to my point of view I think the reason why it is not capturing the value automatically is because there is no onChange function available in react-draft-wysiwyg rather it has onEditorStateChange function which could e possible reason for not handling by antd. So, I was just curious if there is some way to remap the function from onEditorStateChange to onChange and if I am thinking right than it has to work after changing the function. Would appreciate your comments on it, I am actually more curious about what I am thinking is right or not rather than just make this thing work, because this will work somehow but why antd is not capturing it automatically is my actual question. As, it relates to this problem so I have mentioned the problem as well.

1

There are 1 answers

2
NoNam4 On

I've done exactly the same you want to achieve, in my case I'm using tinyMCE editor but it's almost the same thing.

You can use a ref in your editor and on form onFinish event you can retrieve editor value:

const [form] = Form.useForm()
const editorRef = useRef(null)

function onFormSubmit(formData) {
  // maybe the method to get editor content is different
  // I've done a quick google search and found this
  const editorContent = editorRef.current?.getCurrentContent() ?? ''

  console.log({
    ...formData,
    editorContent
  })
}

return (
  <Form onFinish={ onFormSubmit }>
    <Editor
      ref={ editorRef }
      ... other props
    />

    <Form.Item name=" ... ">
      ... form itens
    </Form.Item>
    
    <Button htmlType="submit">Submit</Button>
  </Form>
)