reactjsdraftjsreact-draft-wysiwyg

DraftJS WYSIWYG - Cannot Load Content Into Component


I'm trying to load a DraftJS WYSIWYG Editor component as an already-populated text field with the following: <p>Hello World</p>.

export default class RichTextComponent extends Component {
  
    constructor(props) {
      super(props)
      const contentState = convertFromHTML('<p>Hello World</p>')
      const editorState = EditorState.createWithContent(contentState)
  
      this.state = {
        contentState,
        editorState
      }
    }

    render() {
        const { editorState } = this.state
        return <Editor editorState={editorState} />
      }
}

But when the component is rendered, I get the following error:

Uncaught Invariant Violation: invalid RawDraftContentState


Solution

  • The correct way to achieve desired result is:

    import htmlToDraft from 'html-to-draftjs';
    
    export default class RichTextComponent extends Component {
      
        constructor(props) {
            super(props)
            const contentBlocks = htmlToDraft('<p>Hello World</p>')
            const contentState = ContentState.createFromBlockArray(contentBlocks)
            const editorState = EditorState.createWithContent(contentState)
        
            this.state = {
              editorState
            }
          }
    
        render() {
            const { editorState } = this.state
            return <Editor editorState={editorState} />
          }
    }