3

I have a JSON table with posts. Content is delivered in HTML, and when I try to render it in React:

  return (
    <article>
      <h2><a href={post.link}>{post.title.rendered}</a></h2>
      <div className="post__content">{post.content.rendered}</div>
    </article>
  )

I am getting full HTML markup printed (escaped). What should I do?

Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112

2 Answers2

14

Try using dangerouslySetInnerHTML

<article>
  <h2><a href={post.link}>{post.title.rendered}</a></h2>
  <div className="post__content" dangerouslySetInnerHTML={{__html: post.content.rendered}}></div>
</article>
james emanon
  • 11,185
  • 11
  • 56
  • 97
  • 1
    I know about this method, but isn't it dangerous? On the other hand, there won't be any user-written posts. – Tomek Buszewski Mar 28 '16 at 20:20
  • I've always used it, but I've always had control or knew the origin of the date I was rendering. So, yeah - its a touch choice. My thought outside of this would be to strip all html characters then deal with beautification on your end. – james emanon Mar 28 '16 at 20:33
1

If you're looking to do something like code-snippets, you can just use a string literal, as opposed to dangerouslySetInnerHTML:

var Snippet = React.createClass({
  render: function() {
    return (
      <div>
        {`
        <pre><code>
                  <h4>I am code!</h4>
                </code></pre>
        `}
      </div>
    );
  }
});

ReactDOM.render(
  <Snippet/>,
  document.getElementById('container')
);
markthethomas
  • 4,391
  • 2
  • 25
  • 38