Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>         );       }     } 
like image 711
Ewan Valentine Avatar asked Apr 18 '16 08:04

Ewan Valentine


2 Answers

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.

like image 72
Victor Avatar answered Sep 22 '22 06:09

Victor


Ewan. I am also playing with Draft.js and came across the same problem. Actually, Victor has provided a great solution.

Here are two libraries that I found. The one mentioned by Victor has more stars on GitHub.

https://github.com/sstur/draft-js-export-html

https://github.com/rkpasia/draft-js-exporter

I just want to add that there is a way to print out the content (in JSON format) without using an external library. It is documented under the Data Conversion session.

Here is how I print out user input using the "convertToRaw" function

console.log(convertToRaw(yourEditorContentState.getCurrentContent()));  

Make sure you imported the convertToRaw function from Draft.js by writing:

import { convertFromRaw, convertToRaw } from 'draft-js'; 

Here is a great blog written by rajaraodv named How Draft.js Represents Rich Text Data. It explained data conversion in detail.

like image 29
Jun Yin Avatar answered Sep 26 '22 06:09

Jun Yin