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?
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.
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.
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.
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(); }
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()); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With