0

I have a use case where I have to render an HTML template onto an editor. I am exploring draftjs for the same. I have the basic setup done and have draftjs editor rendering for simple text.

But if I pass an HTML string to same Editor component I get below exception.

DraftEditorContents-core.react.js:80 Uncaught TypeError: nextEditorState.getDirectionMap is not a function
    at DraftEditorContents.shouldComponentUpdate (DraftEditorContents-core.react.js:80)
    at checkShouldComponentUpdate (react-dom.development.js:11345)
    at updateClassInstance (react-dom.development.js:11754)
    at updateClassComponent (react-dom.development.js:13153)
    at beginWork (react-dom.development.js:13824)
    at performUnitOfWork (react-dom.development.js:15863)
    at workLoop (react-dom.development.js:15902)
    at HTMLUnknownElement.callCallback (react-dom.development.js:100)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
    at invokeGuardedCallback (react-dom.development.js:187)

Any idea what is it I need to do to get this working on draft? If draftjs is not ideal for this so you suggest any other library as an alternative?

halfer
  • 19,824
  • 17
  • 99
  • 186
bluefalcon
  • 505
  • 1
  • 5
  • 21

1 Answers1

0

To pass HTML string to editor you can use convertFromHTML function provided by Draftjs editor :

componentWillMount() {
    const compositeDecorator = new CompositeDecorator([
      {
        strategy: this.handleStrategy,
        component: HandleSpan,
        readOnly: true,
      },
    ]);
    const { value } = this.props;
    if (value) {
      const blocksFromHTML = convertFromHTML(value.replace(/(?:\r\n|\r|\n)/g, '<br /><br />'));
      const state = ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap,
      );
      this.state = {
        editorState: EditorState.createWithContent(
          state,
          compositeDecorator,
        ),
      };
    } else {
      this.state = {
        editorState: EditorState.createEmpty(),
      };
    }
  }

and then you can use this.state.editorState as props in render function:

<Editor
    editorState={this.state.editorState}
/>
Piyush Zalani
  • 3,686
  • 1
  • 13
  • 29