-1

We can use dangerouslySetInnerHTML in the react render to load the html string properly in the dom. But how can we do if we can some javascript or jquery code in the html string. For example below. The html with javascript/jquery comes as api response.

var htmlString = "<div>Hello</div><script>alert('hello')</script>"
Rahul Tailwal
  • 3,183
  • 3
  • 14
  • 27

1 Answers1

0

You can find the scripts sections and other sections with:

  var div = document.createElement('div');
  div.innerHTML = htmlString;
  var scripts = div.getElementsByTagName('script');
  var i = scripts.length;
  while (i--) {
    scripts[i].parentNode.removeChild(scripts[i]);
  }

You can then use scripts and div.innerHTML

There are a number of ways to add the script tag, some of which you can see here:

Adding script tag to React/JSX

Community
  • 1
  • 1
Frazer Kirkman
  • 1,003
  • 1
  • 14
  • 23