Reputation: 9417
I'm using react.js
to render a <script>
on an html page. Within this script, there is a javascript function that I need to call from within my react class.
This is what I have...
class Example extends React.Component {
componentWillMount() {
//render a script
const script = document.createElement("script");
script.src = "http//random_source.js";
render(){
//call method from the script rendered
window.someMethod();
return(
<div>{this.componentWillMount}</div>
);
}
}
So componentWillMount()
is rendering my script on the html page, and within the render()
I'm calling window.someMethod()
where someMethod
is located inside the rendered script.
Is this possible using react? If not is there any work around?
Upvotes: 1
Views: 4542
Reputation: 2944
Scripts are asynchronous, so you need to wait for the script to be loaded and parsed. When this completes, the onload
callback/event will be triggered
class Example extends React.Component {
getInitialState(){
return {loaded:false} //initially not loaded
}
componentWillMount() {
//render a script
const script = document.createElement("script");
script.src = "http//random_source.js";
//when the script loads, we're ready to go, so change state
script.onload = (function(){
this.setState({loaded: true})
}).bind(this);
//append the script to the DOM
//you should take care not to include it twice
// and if include to setState to loaded just as script.onload does
document.getElementsByTagName('head')[0].appendChild(script);
}
render(){
if(!this.state.loaded){
return (<div>Loading...</div>);
}
//call method from the script rendered
window.someMethod();
return(
<div>{this.componentWillMount}</div>
);
}
}
Upvotes: 1
Reputation: 8114
Yes this is indeed possible using reactJS. I have implement few scroll events using this. The only condition is that your javascript should load before your reactjs component else undefined error would be thrown.
But if this is required only for this particular component you can implement it the component class only.
Upvotes: 0