简体   繁体   中英

DraftJS React-Hook-Form - submitting Editor as input

I'm working with react-hook-form and I want to pass a rich text editor as input. I've included the RichText component below which is a standard Draft-js implementation, but when I click submit, I get "draft: undefined" instead of the text inside the editor

index.js import { useForm, Controller } from 'react-hook-form';

const JobPostForm = () => {

    const { register, handleSubmit, errors, control } = useForm({
    });

    return(
        <Controller
            as={<RichText />}
            name="draft"
            control={control}
        />
    )
}

RichText.js

<Editor
      customStyleMap={styleMap}
      ref={editor}
      editorState={editorState}
      onChange={editorState => setEditorState(editorState)}
 />

https://react-hook-form.com/api#Controller

I have updated the doc to include draft-js example:

https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r?file=/src/index.js

you should use Controller's render prop

import React from "react";
import { Controller } from "react-hook-form";
import { Editor } from "draft-js";

function RichText({ control }) {
  return (
    <div
      style={{
        border: "1px solid #ccc",
        minHeight: 30,
        padding: 10
      }}
    >
      <Controller
        name="DraftJS"
        control={control}
        render={({ value, onChange }) => (
          <Editor editorState={value} onChange={onChange} />
        )}
      />
    </div>
  );
}

export default RichText;

Just adding to the answer posted by @Bill I would recommend using onEditorStateChange as the prop for the Editor component instead of onChange . This is why you are getting this error

TypeError: Cannot read property 'isOnChange' of undefined".

Here is the updated code:

import React from "react";
import { Controller } from "react-hook-form";
import { Editor } from "draft-js";

function RichText({ control }) {
  return (
    <div
      style={{
        border: "1px solid #ccc",
        minHeight: 30,
        padding: 10
      }}
    >
      <Controller
        name="DraftJS"
        control={control}
        render={({ value, onChange }) => (
          <Editor editorState={value} onEditorStateChange={onChange} />
        )}
      />
    </div>
  );
}

export default RichText;

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