Home > Software engineering >  Display HTML on React
Display HTML on React

Time:04-07

I have a React rich text editor which saves long description state as HTML text. I am trying to display the long description on product pages. How do I parse it for it is displaying the HTML text rather than converting it.

It's displaying like this rather than parsing and converting the HTML

<p>hahahah baba is yellow <strong>kkkk very yellow</strong></p><p><strong>ichoo </strong></p>

CodePudding user response:

You can assign this html to a variable and print by using the dangerouslySetInnerHTML prop.

eg

const html = '<p>hahahah baba is yellow <strong>kkkk very yellow</strong></p><p><strong>ichoo </strong></p>';

<div dangerouslySetInnerHTML={{__html:html}}></div>

CodePudding user response:

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

function createMarkup() {
  return {__html: '<p>content...</p>'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

Example snippet: https://codesandbox.io/s/stoic-matan-kzzydv?file=/src/App.js

CodePudding user response:

You can use dangerouslySetInnerHTML as mentioned in React docs

I use react-render-html in my projects.

A sample code will look like this

import renderHTML from 'react-render-html';
 
renderHTML("<a class='github' href='https://github.com'><b>GitHub</b></a>")
  • Related