How do I use external script that I add to react JS?
You can use React Helmet npm
step 1 : npm i react-helmet
step 2 :
<Helmet>
<script src="/path/to/resource.js" type="text/javascript" />
</Helmet>
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());
});