Home > Net >  Creating new instances of external script in React
Creating new instances of external script in React

Time:05-17

I've been stuck with integrating external script in my React application. The idea is to use external html/js widget that will suggest addresses based on the data in the input field.

The widget requires two things:

  1. <script type="text/javascript" src="https://some.address.com/widget.min.js"></script> - must be inside the html head tag.
  2. <script> var widget = new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});</script> - must be inside the html body tag.

My question is - how can I create new instance of an external script if the given item is not imported as a module? I know that the first part can be resolved with useEffect hook. However, if I try to make new instance of jsWidget, the code editor throws an error saying that jsWidget is not defined.

The given widget works fine in pure html. For example:

<html>
<head>
<script1></script1>
</head>
<body>
<script2></script2>
</body>
</html>

I've been stuck with this for a long time now and I can't figure out a way how to fix this. I would be really thankful if someone could give some advice.

CodePudding user response:

maybe not the best method. i think it'll works

var script1 = document.createElement("script");
script1.type = "text/javascript";
script1.src = "https://some.address.com/widget.min.js";

var script2 = document.createElement("script");
script2.innerHTML = 'new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});';

document.head.appendChild(script1);
setTimeout(() => { // maybe it takes time for the first one
    document.body.appendChild(script2);
}, 1337)
  • Related