I am trying to load an external script in the middle of my React Component.
import React from 'react';
class Test extends React.Component {
componentDidMount() {
const script = document.createElement("script");
script.src = "http://example.com/form.js";
this.myDiv.appendChild(script);
}
render() {
return <div ref={e => (this.myDiv = e)} />;
}
}
Unfortunately the external script contains document.write
. Therefore it gives me an error when I try to load it :
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
The error is quite easy to understand. As the script is run after the document as been parsed, it cannot use document.write
.
What are my options to remedy this problem ?
What I did so far :
So far I have tried using Krux's postscribe
module but failed to make it work :
import React from 'react';
class Test extends React.Component {
render() {
return (
<div>
<div id="myDiv" />
<script dangerouslySetInnerHTML={{
__html: postscribe(
"#myDiv",
<script src="http://example.com/form.js" />
)
}} />
</div>
);
}
}
Any help much appreciated