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.

2
  • Check out this related link Commented Mar 7, 2016 at 22:15
  • That link is not suitable for me Commented Mar 7, 2016 at 23:56

3 Answers 3

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*/;
    };
}
Sign up to request clarification or add additional context in comments.

Comments

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>
  );
}

1 Comment

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
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>
}

1 Comment

It's a good project but I think it needs updating. Placing the <Helmet> component in JSX shows a warning: react-dom.development.js:12466 Warning: componentWillMount has been renamed, and is not recommended for use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.