CoolDog
CoolDog

Reputation: 137

How to display HTML received in JSON using React

JSON

var obj = {
   content: "<p class="p1">Sample p tag one.</p> <p class="p1">Also 
   another paragraph sample.</p> <p><b>sample text</b></p> <p>More info <a 
   title="" href="https://www.google.com/" 
   target="_blank" rel="noopener"><em>THE WORK AHEAD: MACHINES, SKILLS AND 
   U.S. LEADERSHIP</em></a></p>"
};

How would I render this code in react? It shows all of the html tags.

Upvotes: 2

Views: 297

Answers (3)

Paul Redmond
Paul Redmond

Reputation: 3296

You need to parse the HTML.

You can do this through dangerouslySetInnerHTML but it's safer to sanitize it first using something like html-react-parser.

import Parser from 'html-react-parser';

Inside you render function:

<div>{Parser(obj.content)}</div>

Upvotes: 2

Ramon Balthazar
Ramon Balthazar

Reputation: 4260

Through dangerouslySetInnetHTML.

const htmlString = '<p>My html</p>';

const innerHtmlObject = {
  __html: htmlString,
};

<div dangerouslySetInnerHTML={innerHtmlObject} />

Note: This is a bad practice that can lead to security vulnerability!

Upvotes: 4

Adnan
Adnan

Reputation: 1707

You can try this

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

Upvotes: 2

Related Questions