Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use external script that I add to react JS?

I would like to add to my react component a

<script>http://xxx.xxx/XX.js</script>

I know I can simply add it using JSX , what I don't know is how to use it,

for instance this script has a function called A.Sort() , how can I call it and use it from a component?

like image 986
metalice Avatar asked Nov 20 '18 15:11

metalice


People also ask

How do I use an external script?

Using an external script is easy , just put the name of the script file(our . js file) in the src (source) attribute of <script> tag. External JavaScript file can not contain <script> tags.

How do I load an external script dynamically in react?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.

How do you include external HTML file in react JS?

If you want to include static html in ReactJS. You need to use html-loader plugin if you are using webpack to serve your react code. That is it. Now you can use static html files to load your html files in react.


2 Answers

You can load the script asynchronously and access it on load.

componentDidMount() {   const script = document.createElement("script");   script.src = "/static/libs/your_script.js";   script.async = true;   script.onload = () => this.scriptLoaded();    document.body.appendChild(script); } 

It should get attached to the window.

 scriptLoaded() {    window.A.sort();  } 

or

scriptLoaded() {   A.sort(); } 
like image 197
Flow Avatar answered Sep 30 '22 19:09

Flow


You can include the tag in the /public/index.html, and then use the script as you use it in normal JS code, following example for if you want to use jQuery:

in your public/index.html include the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

And then anywhere you can use the jQuery functionality as usual:

window.$("#btn1").click(function(){   alert("Text: " + $("#test").text()); }); 
like image 33
Bilal Avatar answered Sep 30 '22 17:09

Bilal