Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Script tag not working when inserted using dangerouslySetInnerHTML

I'm trying to set html sent from my server to show inside a div using dangerouslySetInnerHTML property in React. I also have script tag inside it and use functions defined in same inside that html. I have made example of error in JSFiddle here.

This is test code:

var x = '<html><scr'+'ipt>alert("this.is.sparta");function pClicked() {console.log("p is clicked");}</scr'+'ipt><body><p onClick="pClicked()">Hello</p></body></html>';  var Hello = React.createClass({   displayName: 'Hello',   render: function() {     return (<div dangerouslySetInnerHTML={{__html: x}} />);   } }); 

I checked and the script tag is added to DOM, but cannot call the functions defined within that script tag. If this is not the correct way is there any other way by which I can inject the script tag's content.

like image 479
meteors Avatar asked Feb 24 '16 22:02

meteors


People also ask

Do script tags work in React?

Both React and the application code can stay as <script> tags with no changes.

How do you use dangerouslySetInnerHTML React?

dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.

Can we use dangerouslySetInnerHTML?

​ dangerouslySetInnerHTML is mostly used in any application where you need to render formatted text in a div element. Also, you can use it to render content exactly as you have formatted it. For instance, let's consider a blog application.

How do I load an external script dynamically in React?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.


1 Answers

I created a React component that works pretty much like dangerouslySetInnerHtml but additionally it executes all the js code that it finds on the html string, check it out, it might help you:

https://www.npmjs.com/package/dangerously-set-html-content

like image 164
Cristofer Flores Avatar answered Sep 28 '22 08:09

Cristofer Flores