Draft.js and stateToHTML, how to render output html in react component?

4.5k Views Asked by At

I've got my Draft js editor working fine, it saves to my database, using convertToRaw(editorState1.getCurrentContent()), and I am getting it back and converting it to HTML using draft-js-export-html and stateToHTML(convertFromRaw(dbContent.content.text01)).

So far so good... but now I have raw HTML that I want to display in my react component, and here comes the trouble.

Just rendering it with {props.text01} outputs it as a string and turns into <p>adfasfadfs</p> as text.

Obviously I want it to render as HTML. How do I do that?

I have looked at dangerouslySetInnerHTML but I would prefer not having ANOTHER plugin just to get my Draft js working the way I want it to.

Am I going at it the wrong way, or is dangerouslySetInnerHTML the only way to do it?

2

There are 2 best solutions below

1
On BEST ANSWER

As described in this answer, React will escape HTML by default (that's why it's just rendered as a string). But you can force the rendering by using the dangerouslySetInnerHTML property. You'd just have to take potential XSS attacks into consideration.

If Draft is already installed, another way to just simply render the content is to use the readOnly prop on the DraftEditor.

3
On

you can use this npm module. link is link npm install --save html-to-react

Examples

Simple The following example parses each node and its attributes and returns a tree of React elements.

var ReactDOMServer = require('react-dom/server');
var HtmlToReactParser = require('html-to-react').Parser;

var htmlInput = '<div><h1>Title</h1><p>A paragraph</p></div>';
var htmlToReactParser = new HtmlToReactParser();
var reactElement = htmlToReactParser.parse(htmlInput);
var reactHtml = ReactDOMServer.renderToStaticMarkup(reactElement);

assert.equal(reactHtml, htmlInput); // true