2

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.

3 Answers 3

4

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!

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

Comments

2

You can try this

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

Comments

2

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>

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.