1
votes

This is my editor.js

I have sample JSON data in const content. What I want to do is that , initially when I open my editor , it should render the initial content in the variable content. But I have no idea how to update the editorState as it is immutable.

import React, { Component } from 'react';
import { EditorState, convertToRaw, convertFromRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';


const content = {"blocks":[{"key":"5ngeh","text":"hi there !!!!!","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}};

This is my BlogEdit component:

class BlogEdit extends Component {
constructor(props) {
    super(props);
    const contentState = convertFromRaw(content);
    console.log(contentState);
    this.state = {
    editorState: EditorState.createEmpty(),       //I need to change this to actually render the content of content variable in editor
    contentState,
    }
    console.log(contentState);
}

This function is responsible for changing the JSON in content according to editorState

onContentStateChange: Function = (contentState) => {
    this.setState({
    contentState,
    });
};

And this is the render part...

render() {
    const { editorState } = this.state;
    const { contentState } = this.state;
    return (
    <div>
        <Editor
        editorState={editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        onContentStateChange={this.onContentStateChange}
        />

    </div>
    );
}
}

export default BlogEdit;

So what actually I'm supposed to do?

3

3 Answers

2
votes

Editor component has a prop name initialContentState. You can pass the contentstate here.

2
votes

Instead of EditorState.createEmpty(), you can create with the content,

 let editorStatewithContent = EditorState.createWithContent(contentState);     
 //Then you set the state 
 this.state = {
   editorState:  editorStatewithContent      
}

You may have to go through the document, it has everything well explained.

0
votes

If you are using redux and your editor state hasn't entityMap object, it will throw an error.

so you can do that

const content = convertFromRaw({...contentState, entityMap: {}})

It will also solve your problem of invalid RawDraftContentState

No need to set any initialContentState, you can achieve it without setting that value

this.setState({
    editorState: EditorState.createWithContent(content)
})