reactjsreact-draft-wysiwyg

How to set initial editor state in react draft wysiwyg


While storing the data from react-draft-wysiwyg text editor to server side I convert it to JSON using this function.

content = JSON.stringify(
  convertToRaw(state.editorState.getCurrentContent()),
);

When I retrieve the data it is in the JSON like this

"{\"blocks\":[{\"key\":\"b4n4u\",\"text\":\"Hi \",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}},{\"key\":\"bp5jr\",\"text\":\"fgfgfgfgfgfg\",\"type\":\"header-two\",\"depth\":0,\"inlineStyleRanges\":[{\"offset\":0,\"length\":12,\"style\":\"fontsize-8\"}],\"entityRanges\":[],\"data\":{}},{\"key\":\"81j28\",\"text\":\"\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}},{\"key\":\"1nljr\",\"text\":\"dfdfdf\",\"type\":\"unordered-list-item\",\"depth\":0,\"inlineStyleRanges\":[{\"offset\":0,\"length\":6,\"style\":\"fontsize-8\"}],\"entityRanges\":[],\"data\":{}},{\"key\":\"b629m\",\"text\":\"dfdfdf\",\"type\":\"unordered-list-item\",\"depth\":0,\"inlineStyleRanges\":[{\"offset\":0,\"length\":6,\"style\":\"fontsize-8\"}],\"entityRanges\":[],\"data\":{}},{\"key\":\"3afsd\",\"text\":\"dfdfdf\",\"type\":\"unordered-list-item\",\"depth\":0,\"inlineStyleRanges\":[{\"offset\":0,\"length\":6,\"style\":\"fontsize-8\"}],\"entityRanges\":[],\"data\":{}},{\"key\":\"1rq6j\",\"text\":\"dfdf\",\"type\":\"unordered-list-item\",\"depth\":0,\"inlineStyleRanges\":[{\"offset\":0,\"length\":4,\"style\":\"fontsize-8\"}],\"entityRanges\":[],\"data\":{}},{\"key\":\"536hu\",\"text\":\"df\",\"type\":\"unordered-list-item\",\"depth\":0,\"inlineStyleRanges\":[{\"offset\":0,\"length\":2,\"style\":\"fontsize-8\"}],\"entityRanges\":[],\"data\":{}}],\"entityMap\":{}}",

Now, I want this to be the initialState of editor in another page.

So I tried using defaultEditorState as mentioned in docs https://jpuri.github.io/react-draft-wysiwyg/#/docs

<Editor
        defaultEditorState={convertFromRaw(JSON.parse(post.content))}
        editorState={state.editorState}
        wrapperClassName='blogpost-text-editor-wrapper'
        editorClassName='blogpost-text-editor'
        toolbarClassName='blogpost-text-editor-toolbar'
        onEditorStateChange={onChange}
      />

But it's not working. The EditorState page from draft.js docs is missing so I don't know how to create a EditorState object. Please help me with this.

Any help will be highly appreciated.


Solution

  • I found a way to do that. Assuming post.content has ContentState we can initialize EditorState like this.

      const [state, setState] = useState({
        editorState: EditorState.createWithContent(
          convertFromRaw(JSON.parse(post.content)),
        ),
      });