Home > Net >  How to render HTML tags in REACT NATIVE
How to render HTML tags in REACT NATIVE

Time:10-28

I want to show news in my react native application but the content from API is in HTML. So, Please can you tell me how to render HTML without any library.

  "content": "<ul><li>Bitcoin, in terms of market value, rose 4.6% to $53,859.6.</li><li>It passed $50,000 mark for first time in four weeks on Tuesday. </li><li>Bitcoin fell below $50,000 in early September.</li>"
    

CodePudding user response:

Without library you can render HTML using dangerouslySetInnerHTML:

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

However, this is not recommended, because it may be used for a cross-site scripting (XSS) attack

CodePudding user response:

const yourDataObject = {
    "content": "<ul><li>Bitcoin, in terms of market value, rose 4.6% to $53,859.6.</li><li>It passed $50,000 mark for first time in four weeks on Tuesday. </li><li>Bitcoin fell below $50,000 in early September.</li>"
}

const area = document.getElementById("area")
area.innerHTML = yourDataObject.content;
<div id="area"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Decide where you want to render your HTML. In the example below I am going to render the content into the div tag that has an id attribute of "area".

<div id="area"></div>

In your JavaScript, you can select the element with document.getElemenyById and pass in the id attribute value. Next target the innerHtml of the selected div element and set it to be your content.

const yourDataObject = {
    "content": "<ul><li>Bitcoin, in terms of market value, rose 4.6% to $53,859.6.</li><li>It passed $50,000 mark for first time in four weeks on Tuesday. </li><li>Bitcoin fell below $50,000 in early September.</li>"
}

const area = document.getElementById("area")
area.innerHTML = yourDataObject.content;

Note

Always be sure you trust the source of the HTML you are choosing to render in your site. If you do not control the source it is possible that you could render malicious code into your site.

  • Related