Render raw HTML with script tag using reactjs
Rendering raw HTML without React recommended method is not a good practice. React recommends method dangerouslySetInnerHTML
to render raw HTML.
Reactjs highly discourage this due to security reasons. Following is the recommended way of injecting raw HTML in DOM using reactjs.
let rawHTMLCode = "<div>This wil be rendered</div> <script> alert('testing') </script>"; render: function() { return ( <div className="content" dangerouslySetInnerHTML={{__html: rawHTMLCode}}></div> ); }
The above method dangerouslySetInnerHTML
will not render the script tag. This is how it should be. But in case if we need to render a block of HTML that has script tags in it, we can do that too at our own risk.
One use case:
Let say in a reactjs project we need to call an API and the API response is providing us a block of HTML that has script tags in it. We need to render the entire block of HTML.
How to render HTML block with script tag?
We can render a block of HTML with script tag using this package: dangerously-set-html-content
. Remember we will have to do it at our own risk. https://www.npmjs.com/package/dangerously-set-html-content
Install the package
$ yarn add dangerously-set-html-content // or $ npm install --save dangerously-set-html-content
Usage in the code:
import React from 'react' import InnerHTML from 'dangerously-set-html-content' function Example { const html = ` <div>This wil be rendered</div> <script> alert('HTML with script tag rendered') </script> ` return ( <InnerHTML html={html} /> ) }