'Html parser package in React (react-html-parser) is stripping <script> tag

In my React app I am using react-html-parser.

And use it like:

import ReactHtmlParser from 'react-html-parser';

<div>
  {ReactHtmlParser(html)}
</div>

From the backend I get some html:

(function(... a custom function here --->);

But if I check the dom everything is rendered, except the <script> tag?

I tried the suggestion from this thread:

import ReactHtmlParser, { Options } from 'react-html-parser';

const options = {
    replace: (domNode: { type: string; attribs: { src: string } }) => {
      if (domNode.type === 'script') {
        const script = document.createElement('script');
        script.src = domNode.attribs.src;
        document.head.appendChild(script);
      }
    },
  };

return (
    <div>
      {ReactHtmlParser(html, options as Options)}
    </div>
  );

But it's still not injecting the script?

Update Trying the answer from @Nemanja. Due to Typescript I had to change it a bit:

const transform: Transform = (node, index) => {
    if (node.type === 'script' && node.children?.length) {
      console.log('Node', node);
      return <script key={index}>{node.children[0].data}</script>;
    }
    return null;
  };

  const options = {
    transform,
  };

But now its not rendering the actual HTML anymore?



Solution 1:[1]

To load a script, you will need to programmatically create and append a script element using transfom method from react-html-parser library. Code below shoud work as expected.

import React, { DOMElement } from 'react';
import ReactHtmlParser, { Options } from "react-html-parser";



 const html =
   "<div class='css-class' data-src='/event/66478667'></div>  <script src='something'>(function(d, s, id) {var js,ijs=d.getElementsByTagName(s)[0];if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src='https://embed.widget.js';ijs.parentNode.insertBefore(js, ijs);}(document, 'script', 'my-js'));</script>";


  const options = {
    transform : function transform(node :any, index:any) {
       if ( node.type === 'script') {
          return <script key={index} src={node?.attribs?.src}>{node?.children[0]?.data}</script>;
      }
    }
  };



export default function App() {
  return (
    <div>
      {ReactHtmlParser(html, options as Options)}
    </div>
  );
}

Here is the output of following code :

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1