I want to load the script from a CDN and then execute a function exposed by that script in React:
componentWillMount() {
console.log('componentWillMount is called');
const script = document.createElement('script');
script.src = 'https://foo.azurewebsites.net/foo.js';
document.body.appendChild(script);
}
componentDidMount() {
console.log('componentDidMount is called');
window.foo.render({
formId: '77fd8848-791a-4f13-9c82-d24f9290edd7',
}, '#container');
}
render() {
console.log('render is called');
return (
<div id="container"></div>
);
}
The script sometimes takes time to load (generally first time) and when componentDidMount() is called "foo" is not available and I get an error like this:
TypeError: Cannot read property 'render' of undefined
How can I assure that componentDidMount() is called once the script is loaded successfully?
<script>tags?renderfunction first.onloadfunctionality when appending scripts to the document body, so you could have some say a boolean in the component's state to keep track of load status, and in theonloadfunction set the state's 'loaded' boolean to true. Then in your render function check the state value. Here's a google search: google.com.au/…*