I can't get the html output from draft-js?

Ewan Valentine picture Ewan Valentine · Apr 18, 2016 · Viewed 24.7k times · Source

I've been playing around with draft-js by Facebook, but I can't actually figure out how to get the html output of the editor. The console.log in the following example outputs some _map properties, but they don't seem to contain my actual content?

class ContentContainer extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          value: '',
          editorState: EditorState.createEmpty()
        };
        this.onChange = (editorState) => this.setState({editorState});
        this.createContent = this.createContent.bind(this);
      }

      createContent() {
        console.log(this.state.editorState.getCurrentContent());
      }

      render() {
        const {editorState} = this.state;
        const { content } = this.props;
        return (
          <Template>
            <br /><br /><br />
            <ContentList content={content} />
            <div className="content__editor">
              <Editor editorState={editorState} onChange={this.onChange} ref="content"/>
            </div>
            <FormButton text="Create" onClick={this.createContent.bind(this)} />
          </Template>
        );
      }
    }

Answer

Victor picture Victor · Apr 28, 2016

There is a handy library I used, draft-js-export-html. Import the library and you should be able to see HTML once you invoke the function, stateToHTML:

console.log(stateToHTML(this.state.editorState.getCurrentContent()));

I'm pretty new to React so hopefully this works for you. I looked under the hood of contentState and there is a fair bit going on there that makes using a library to parse out the entities that much more enticing.

The author, sstur, answers a tangentially-related question where I learned about his libraries.