5

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?

0

2 Answers 2

17

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I know about this method, but isn't it dangerous? On the other hand, there won't be any user-written posts.
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.
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')
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.