Converting HTML strings to JSX in React JS

Total
0
Shares

React JS prevents loading html into the application. This is because they are prone to XSS (cross site script) attack. But if you trust the source and there is genuine need to convert html string to JSX, then you may use dangerouslySetInnerHTML prop provided by React.

Code Example

Suppose you have an html string which you want to convert to JSX –

const htmlString = `
<div>
  <h3>List of Avengers</h3>
  <ol>
    <li>Captain America</li>
    <li>Ironman</li>
    <li>Hulk</li>
    <li>Thor</li>
    <li>Spiderman</li>
    <li>Vision</li>
    <li>Black Widow</li>
    <li>Scarlet Witch</li>
    <li>Hawkeye</li>
    <li>Falcon</li>
  </ol>
</div>
`

As you can see that in our html string nothing is dangerous. There are no scripts, no absolute or fixed positioning, no invalid tags etc. So, its safe to use it in our JSX. We will use dangerouslySetInnerHTML property.

export default function App(){
  const htmlString = `
    <div>
      <h3>List of Avengers</h3>
      <ol>
        <li>Captain America</li>
        <li>Ironman</li>
        <li>Hulk</li>
        <li>Thor</li>
        <li>Spiderman</li>
        <li>Vision</li>
        <li>Black Widow</li>
        <li>Scarlet Witch</li>
        <li>Hawkeye</li>
        <li>Falcon</li>
      </ol>
    </div>
  `

  return(
    <div dangerouslySetInnerHTML={{__html: htmlString}} />
  )
}

    Tweet this to help others

Live Demo

Open Live Demo