Render the HTML raw in React app

In the case that you have to render a dynamic HTML from database or somewhere, when you add the HTML raw as a variable into your React app, it just render the string, consider the example bellow:

 
import React from 'react'

const RenderHTML = () => {
  const html = '<div><a href="#">This is example</a></div>'
  return (
    <div>
      Please click this link: {html}
    </div>
  )
}

export default RenderHTML;

Copy this code


The result will be:



Solution: Use dangerouslySetInnerHTML method in React, use it very easy:

 
import React from 'react'

const RenderHTML = () => {
  const createMarkup = htmlString => ({ __html: htmlString });
  const html = '<div><a href="#">This is example</a></div>'
  return (
    <div>
      Please click this link: <div dangerouslySetInnerHTML={createMarkup(html)} />
    </div>
  )
}

export default RenderHTML;

Copy this code


The result will be:



© 2019 4codev

Created with love by Sil.