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> ); } }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With