Dmitriy Kostenko
Dmitriy Kostenko

Reputation: 33

Adding JS script tag to React

I have a script.js file on the server which is written in pure javascript (vanilla) and returns HTML form with some functionality. I download it by first <script> tag and use functions from script.js in second <script> tag in .html file and it is working. But I don't know how to make it run in React. I tried to do so, but not working.

script.js

var lib = lib || (function() {
  var _args = {};

  return {
    init: function(Args) {
      _args = Args;
    },
    func: function() {
      ...some logic and use document.write
      for render
    }
  }
}())

In HTML, it works

<script src='http://someurl.com/checkout'></script>
<script>
  lib.init(...some args);
  lib.func();
</script>

In React, it doesn't work

import React, {
  Component
} from 'react';
import axios from "axios";

class Checkout extends Component {

  state = {}

  componentDidMount = async() => {
    axios.get("http://someurl.com/checkout")
      .then(res => {
        const scriptInit = document.createElement("script");
        scriptInit.src = "http://someurl.com/checkout";
        // or scriptInit.text = res.data;
        scriptInit.type = "text/javascript";
        scriptInit.async = true;
        const scriptFunc = document.createElement("script");
        scriptFunc.text = "lib.init(...); lib.func();";
        scriptFunc.async = true;
        const script = scriptInit.outerHTML + scriptFunc.outerHTML;
        this.setState({
          script
        });
      })

  }

  render() {
    const __html = this.state.script || "";
    return <div id = "checkout"
    dangerouslySetInnerHTML = {
      {
        __html
      }
    }
    />
  }
}

export default Checkout;

Render div tag with all script tags but with 1110 x 0 resolution

Upvotes: 2

Views: 2455

Answers (1)

anuragb26
anuragb26

Reputation: 1475

You need to call the functions after your script loads.You would not need axios for this,you can acheive this using the onload callback for the script load.

componentDidMount(){
 const script = document.createElement("script");
 document.head.appendChild(script);
 script.src = "http://someurl.com/checkout";
 script.async = true;
 script.onload = () => this.runScriptMethods();
}

runScriptMethods(){
  lib.init(...);
  lib.func()
}

Upvotes: 2

Related Questions