Search code examples
react-hook-formdraft-js-plugins

How to use draft-js-plugins in react-hook-form


I am using react-hook-form and draft.js as wysiwiyg. My code where I am using draft-js-plugins:

import React, {useRef} from "react";
import { Controller } from "./src";
import Editor from "@draft-js-plugins/editor";
import createToolbarPlugin from "@draft-js-plugins/static-toolbar";
import "draft-js/dist/Draft.css";
import "@draft-js-plugins/static-toolbar/lib/plugin.css";

const staticToolbarPlugin = createToolbarPlugin();
const { Toolbar } = staticToolbarPlugin;
const plugins = [staticToolbarPlugin];

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

export default RichText;

All is ok, I see plugins. But when I want select word and click to plugin (I, B, U) button show me error

props.getEditorState is not a function

I don't understand how to solve it? I found some examples https://www.draft-js-plugins.com/plugin/static-toolbar .but didn't help

live example on codesandbox


Solution

  • I think you have to place the <Toolbar /> component as a sibling to your <Editor /> component and also pass the ref to it.

    <Controller
      name="DraftJS"
      control={control}
      render={({ value, onChange, ref }) => {
        return (
          <>
            <Toolbar />
            <Editor
              ref={ref}
              editorState={value}
              onChange={onChange}
              plugins={plugins}
            />
          </>
        );
      }}
    />
    

    Edit React Hook Form - V6 - Controller (forked)