5

I am trying load a script dynamically using script tag. But I am not able to do it.

my render method is as below

render() {
<div> 
     <script type="text/javascript" language="javascript" src="//verify.authorize.net/anetseal/seal.js" ></script> 
     <a href="http://www.authorize.net/" id="AuthorizeNetText" target="_blank">Working. Yipee</a> 
</div>
}

I tried to use dangerouslySetInnerHtml but that is also not working.

I require this because, the script that is mentioned uses document.writeln. So I want it to display in this current div. I have no control over the script. It come from a third party.

Abhijith Nagaraja
  • 3,370
  • 6
  • 27
  • 55

3 Answers3

15

I believe you could be more specific on what should be done once the script has been loaded. Something like this should suit you well:

componentDidMount() {
    var aScript = document.createElement('script');
    aScript.type = 'text/javascript';
    aScript.src = " /*URL Goes Here*/ ";

    document.head.appendChild(aScript);
    aScript.onload = function() {
        document.getElementById(" /*DIV ID HERE*/ ").InnerHTML = /*YOUR CODE*/;
    };
}
Carlos_E.
  • 671
  • 8
  • 14
5

You can append the script tag to your body like this:

componentDidMount() {
  var addScript = document.createElement('script');
  addScript.setAttribute('src', '//verify.authorize.net/anetseal/seal.js');
  document.body.appendChild(addScript);
}
render() {
  return (
    <div>
      <a href="http://www.authorize.net/" id="AuthorizeNetText" target="_blank">Working. Yipee</a> 
    </div>
  );
}
Eloy Pineda
  • 2,117
  • 17
  • 22
  • I don't want to append it body element. I want to append it so div element. if I do document.getElementById('id').appendChild(script) it will give me null exception – Abhijith Nagaraja Mar 07 '16 at 23:55
3

You can try to do it using Helmet, https://github.com/nfl/react-helmet

render() {
<div>
  <Helmet>
     <script type="text/javascript" language="javascript" src="//verify.authorize.net/anetseal/seal.js" />
  <Helmet>
  <a href="http://www.authorize.net/" id="AuthorizeNetText" target="_blank">Working. Yipee</a> 
</div>
}
itereshchenkov
  • 247
  • 1
  • 3
  • 8
  • 2
    It's a good project but I think it needs updating. Placing the `` component in JSX shows a warning: `react-dom.development.js:12466 Warning: componentWillMount has been renamed, and is not recommended for use.` – enchance Sep 29 '19 at 06:18