react-draft-wysiwyg - Warning: Can't call setState

3.5k Views Asked by At

I did make a simple react app with react-draft-wysiwyg, but I get a warning.

import React from "react";
import ReactDOM from "react-dom";
import { Editor } from "react-draft-wysiwyg";
import "../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

ReactDOM.render(
  <React.StrictMode>
    <Editor />
  </React.StrictMode>,
  document.getElementById("root")
);

When I click on the editor iget this error in the console, but only when I run it in StrictMode:

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the r component.

I did make a codeSandbox for you: https://codesandbox.io/s/strange-monad-lxtuu?file=/src/index.js:0-295 Try click at the editor and look at the warnings in the console. What have I done wrong?

2

There are 2 best solutions below

3
On BEST ANSWER

The package has some problem with StrictMode. Just remove StrictMode:

import React from "react";
import ReactDOM from "react-dom";
import { Editor } from "react-draft-wysiwyg";
import "../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

ReactDOM.render(
  <Editor />,
  document.getElementById("root")
);
0
On

Try this code, it should work

import { Editor } from 'react-draft-wysiwyg' 
import { EditorState } from 'draft-js'

const [editorState, setEditorState] = useState(EditorState.createEmpty())
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(true)
   return () => {
    setIsMounted(false)
}
}, [])

<div  className="order_detail">
    {isMounted && (
        <Editor
            editorState={editorState}
            wrapperClassName="editor"
            editorClassName="demo-editor"
            onEditorStateChange={setEditorState}
        />
    )}
</div>