Search code examples
javascriptreactjsjsxreact-dom

Generating HTML from markdown only works with dangerouslySetInnerHTML in React App


I am trying to write a simple markdwon previewer. the problem is when I insert the Generated HTML text inside a div in render method like this:

render() {
   return (
     <div>
       {this.state.genHTML}
     </div>  
  );
}

it does not rendered, and displays as it written with its tags just like as if a string. But with dangerouslySetInnerHTML the Generated HTML is got rendered.

I want to know why this occurs?


Solution

  • In general, setting HTML from code is risky(because of cross-site scripting (XSS)), and this is why in React you need to use "dangerouslySetInnerHTML" to set it. This is just a rule that you need to follow if you want to use a React framework.