0

I store some html source code in database, it's a block of code like this:

<div class="content"><h1>Page 1</h1></div>

Now in react I get them in a variable ({this.state.content}), but when I try to render them the source code got displayed as a string. Here's how I use it:

<div>
    {this.state.content}
</div>

On page it just shows the source code directly. How do I get them render as html source code instead of a string?

4
  • Are you talking about rendering html tags on the screen and not have it become a DOM element? If so, you need to escape them. w3schools.com/HTML/html_entities.asp Commented Jan 13, 2018 at 19:04
  • 2
    React provides an attribute for doing this, dangerouslySetInnerHTML. however, from the name, it should be obvious that this isn't a recommended practice, and you should consider more managed alternatives. In general, storing HTML in variables or in your database is a common attack vector. Commented Jan 13, 2018 at 19:06
  • @Andrew It's actually the opposite way. I want it to become a DOM element instead of displaying the html tags on screen. Commented Jan 13, 2018 at 19:14
  • @Claies That worked. Thank you. Also good suggestion, I'll also keep this as bad practice in mind. Commented Jan 13, 2018 at 19:17

1 Answer 1

2

Actually, you are trying to set raw HTML. Try this.

<div dangerouslySetInnerHTML={{__html: this.state.content}}></div>

Duplicate of this question

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.