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?

Suanmeiguo
  • 1,365
  • 3
  • 17
  • 28
  • 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. https://www.w3schools.com/HTML/html_entities.asp – Andrew Jan 13 '18 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. – Claies Jan 13 '18 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. – Suanmeiguo Jan 13 '18 at 19:14
  • @Claies That worked. Thank you. Also good suggestion, I'll also keep this as bad practice in mind. – Suanmeiguo Jan 13 '18 at 19:17

1 Answers1

2

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

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

Duplicate of this question

kazimt9
  • 563
  • 5
  • 11