How to display Draft.js content as HTML
Draft.js is a great way to implement rich text editor with React. At first however, it might not be so clear how to take the rich text representation that is created by Draft.js (=ContentState) and display it as HTML.
You can now get my Draft.js online course for free! Read more.
Draft.js itself doesn’t have an API to convert the content state to HTML. One way to export your content state to HTML is to use npm package draft-js-export-html.
draft-js-export-html provides stateToHtml method which takes ContentState object as parameter and returns the content state as html.
Here is an example for a component that has Draft.js editor and as you type the editor’s content is displayed as html. The conversion from ContentState to HTML is done in the onChange method at line 12.
Here is a working demo: https://github.com/tumetus/draft-js-to-html.
Getting HTML content of Draft.js editor is quite straight forward. If your goal is just to display the content this works fine. However if you are planning on saving the content somewhere else e.g. to a database, this is not the ideal way to do it. For that you should use Draft.js’s own “convertToRaw” method.
Originally published at codepulse.blog on April 1, 2018.