react, access scripts on document [duplicate] - javascript

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?

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());
});

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>

Sometimes we need to work with external js libraries in such cases we need to insert script tags into components, but in react we use jsx, so we can’t add script tags directly just like how we add in HTML.
In this example, we will see how to load an external script file into a head, body elements, or component.
componentDidMount() {
const script = document.createElement("script");
script.async = true;
script.src = "https://some-scripturl.js";
script.onload = () => this.scriptLoaded();
//For head
document.head.appendChild(script);
// For body
document.body.appendChild(script);
// For component
this.div.appendChild(script);
}

You can either modify your index.html file (if you are using one) by adding the required script.
Alternatively, if you can't edit it or you are not using it, there's a bunch of add-ons that solve this, for example react-load-script

After adding this script into your index.html
<script>http://xxx.xxx/XX.js</script>
you might check the available functions if you console.log(window) in App.js (or, wherever you want). Once you check the exact function, then you can use it like
window.A.sort();
I think this could be the simplest way. Just remember that you have to write 'window.' on the left side of your function.

If you want to import script in multiple components, then you can create your own custom hook that allows you to insert script in desired component:
import { useEffect } from 'react'
const importScript = src => {
useEffect(() => {
const script = document.createElement('script')
script.src = src
script.async = true
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [src])
}
export default importScript
Using it on your desired component:
import importScript from 'import-path'
const DesiredComponent = props => {
importScript("/path/to/resource")
// ... rest of the code
}

A hooks version.
import * as React from "react";
function loadError(onError) {
console.error(`Failed ${onError.target.src} didn't load correctly`);
}
function External() {
React.useEffect(() => {
const LoadExternalScript = () => {
const externalScript = document.createElement("script");
externalScript.onerror = loadError;
externalScript.id = "external";
externalScript.async = true;
externalScript.type = "text/javascript";
externalScript.setAttribute("crossorigin", "anonymous");
document.body.appendChild(externalScript);
externalScript.src = `https://externalurl.example.com/external.js?key=9393ABCDEFGH`;
};
LoadExternalScript();
}, []);
return <></>;
}
export default External;

Related

Function not working in app.js but in index.html working library reactjs

I'm having a problem when using a function from the New Relic library,
Can try with codesandbox
If I use this function in public/index.html (command in codesandbox) it works:
screenshot in inspect element working :
well the problem is if I create my own helpers function and create in app.js it doesn't work
below is the app.js file :
import { useEffect } from "react";
import { newRelicConfig } from "./newRelic";
import "./styles.css";
export default function App() {
useEffect(() => {
let script = document.createElement("script");
script.type = "text/jsx";
script.innerHTML = newRelicConfig(
"3277692",
"3277692",
"NRJS-93eea892ddd7204acfd",
"1091749869"
);
document.body.appendChild(script);
}, []);
return (
<div className="App">
<h1>New Relic</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
in file ./newRelic function newRelicConfig
the function of NRJS does not exist :
How to work around a function in app.js like with index.html ?
I'm getting a syntax error while trying to execute your function in newRelix.jsx, so first of all double check the function.
That being said, adding a javascript function in a script tag to your HTML document is not the same as executing that function. You could try adding it as a self invoking function. Also note the the type should be text/javascript (not text/jsx):
useEffect(() => {
let functionBody = newRelicConfig(...); // omitting params here, as they're possibly sensitive
let script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = `(function(){${functionBody}})();`;
document.body.appendChild(script);
}, []);

How do I add an online module/library to my React file? [duplicate]

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?
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());
});
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>
Sometimes we need to work with external js libraries in such cases we need to insert script tags into components, but in react we use jsx, so we can’t add script tags directly just like how we add in HTML.
In this example, we will see how to load an external script file into a head, body elements, or component.
componentDidMount() {
const script = document.createElement("script");
script.async = true;
script.src = "https://some-scripturl.js";
script.onload = () => this.scriptLoaded();
//For head
document.head.appendChild(script);
// For body
document.body.appendChild(script);
// For component
this.div.appendChild(script);
}
You can either modify your index.html file (if you are using one) by adding the required script.
Alternatively, if you can't edit it or you are not using it, there's a bunch of add-ons that solve this, for example react-load-script
After adding this script into your index.html
<script>http://xxx.xxx/XX.js</script>
you might check the available functions if you console.log(window) in App.js (or, wherever you want). Once you check the exact function, then you can use it like
window.A.sort();
I think this could be the simplest way. Just remember that you have to write 'window.' on the left side of your function.
If you want to import script in multiple components, then you can create your own custom hook that allows you to insert script in desired component:
import { useEffect } from 'react'
const importScript = src => {
useEffect(() => {
const script = document.createElement('script')
script.src = src
script.async = true
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [src])
}
export default importScript
Using it on your desired component:
import importScript from 'import-path'
const DesiredComponent = props => {
importScript("/path/to/resource")
// ... rest of the code
}
A hooks version.
import * as React from "react";
function loadError(onError) {
console.error(`Failed ${onError.target.src} didn't load correctly`);
}
function External() {
React.useEffect(() => {
const LoadExternalScript = () => {
const externalScript = document.createElement("script");
externalScript.onerror = loadError;
externalScript.id = "external";
externalScript.async = true;
externalScript.type = "text/javascript";
externalScript.setAttribute("crossorigin", "anonymous");
document.body.appendChild(externalScript);
externalScript.src = `https://externalurl.example.com/external.js?key=9393ABCDEFGH`;
};
LoadExternalScript();
}, []);
return <></>;
}
export default External;

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?
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());
});
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>
Sometimes we need to work with external js libraries in such cases we need to insert script tags into components, but in react we use jsx, so we can’t add script tags directly just like how we add in HTML.
In this example, we will see how to load an external script file into a head, body elements, or component.
componentDidMount() {
const script = document.createElement("script");
script.async = true;
script.src = "https://some-scripturl.js";
script.onload = () => this.scriptLoaded();
//For head
document.head.appendChild(script);
// For body
document.body.appendChild(script);
// For component
this.div.appendChild(script);
}
You can either modify your index.html file (if you are using one) by adding the required script.
Alternatively, if you can't edit it or you are not using it, there's a bunch of add-ons that solve this, for example react-load-script
After adding this script into your index.html
<script>http://xxx.xxx/XX.js</script>
you might check the available functions if you console.log(window) in App.js (or, wherever you want). Once you check the exact function, then you can use it like
window.A.sort();
I think this could be the simplest way. Just remember that you have to write 'window.' on the left side of your function.
If you want to import script in multiple components, then you can create your own custom hook that allows you to insert script in desired component:
import { useEffect } from 'react'
const importScript = src => {
useEffect(() => {
const script = document.createElement('script')
script.src = src
script.async = true
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [src])
}
export default importScript
Using it on your desired component:
import importScript from 'import-path'
const DesiredComponent = props => {
importScript("/path/to/resource")
// ... rest of the code
}
A hooks version.
import * as React from "react";
function loadError(onError) {
console.error(`Failed ${onError.target.src} didn't load correctly`);
}
function External() {
React.useEffect(() => {
const LoadExternalScript = () => {
const externalScript = document.createElement("script");
externalScript.onerror = loadError;
externalScript.id = "external";
externalScript.async = true;
externalScript.type = "text/javascript";
externalScript.setAttribute("crossorigin", "anonymous");
document.body.appendChild(externalScript);
externalScript.src = `https://externalurl.example.com/external.js?key=9393ABCDEFGH`;
};
LoadExternalScript();
}, []);
return <></>;
}
export default External;

How to load script in react component

I am having following script file
<script language="javascript">
document.write('<script language="javascript" src="http://tickettransaction.com/?bid='+bid+'&sitenumber='+site+'&tid=event_dropdown" ></' + 'script>');
</script>
I follow this Adding script tag to React/JSX but it does not work for me...
How do I load the script in my react component?
After a lots of R&D finally I found my solution.
I have used npm postscribe to load script in react component
postscribe('#mydiv', '<script language="javascript" src="http://tickettransaction.com/?bid='+bid+'&sitenumber='+site+'&tid=event_dropdown"></script>')
A 2021 TypeScript example using functional components that works with NextJS
(ensures code only runs client-side)
declare global {
interface Window {
hbspt: any
}
}
export default function Contact() {
useEffect(() => {
if (window && document) {
const script = document.createElement('script')
const body = document.getElementsByTagName('body')[0]
script.src = '//js.hsforms.net/forms/v2.js'
body.appendChild(script)
script.addEventListener('load', () => {
window.hbspt.forms.create({
// this example embeds a Hubspot form into a React app but you can tweak it for your use case
// any code inside this 'load' listener will run after the script is appended to the page and loaded in the client
})
})
}
}, [])
return <div id="hbspt-form" className="p-5"></div>
}
the following method is worked for me. try, hope it will work for you.
basically, you can create a script tag and append it to the body tag. like this--
var tag = document.createElement('script');
tag.async = true;
tag.src = 'THE PATH TO THE JS FILE OR A CDN LINK';
var body = document.getElementsByTagName('body')[0];
body.appendChild(tag);
you can use this on a life cycle hook of react like this.
componentDidMount() {
var loadScript = function (src) {
var tag = document.createElement('script');
tag.async = false;
tag.src = src;
var body = document.getElementsByTagName('body')[0];
body.appendChild(tag);
}
loadScript('PATH TO THE JS FILE OR CDN URL');
}
I recommend using React Helmet. I've used it on a couple of Create-React-Apps, and it allows you to write actual script tags combined with vanilla JS.
It makes the process a lot smoother. So for you it'd be something like this once you've imported React Helmet.
<script language="javascript" src='http://tickettransaction.com/?bid='+ bid + '&sitenumber='+ site +'&tid=event_dropdown' ></ script>
This came to my rescue. This is the easiest way to load Script Tags
https://www.npmjs.com/package/react-script-tag
import ScriptTag from 'react-script-tag';
const Demo = props => (
<ScriptTag src="/path/to/resource.js" />
);
There are other ways to do this too :
https://medium.com/better-programming/4-ways-of-adding-external-js-files-in-reactjs-823f85de3668
Update 2022
Use https://usehooks-ts.com/react-hook/use-script. This also returns status and allows props like removeOnUnmount.
Most of packages to do the job are outdated at the date. I found a solution that maybe can be useful for someone and it´s using a hook with the advantage you can control the state and take action based on it.
import { useEffect, useState } from 'react';
export const useExternalScript = (url) => {
let [state, setState] = useState(url ? "loading" : "idle");
useEffect(() => {
if (!url) {
setState("idle");
return;
}
let script = document.querySelector(`script[src="${url}"]`);
const handleScript = (e) => {
setState(e.type === "load" ? "ready" : "error");
};
if (!script) {
script = document.createElement("script");
script.type = "application/javascript";
script.src = url;
script.async = true;
document.body.appendChild(script);
script.addEventListener("load", handleScript);
script.addEventListener("error", handleScript);
}
script.addEventListener("load", handleScript);
script.addEventListener("error", handleScript);
return () => {
script.removeEventListener("load", handleScript);
script.removeEventListener("error", handleScript);
};
}, [url]);
return state;
};
Use it is simple as do:
const externalScript = 'https://player.live-video.net/1.6.1/amazon-ivs-player.min.js';
const scriptStatus = useExternalScript(externalScript);
useEffect(() => {
if (scriptStatus === 'ready') {
// Do something with it
}
}, [scriptStatus]);
Update 2022 for Class based as well as Functional components.
You can create a function as below and then use it inside componentDidMount:
function loadScript(url, callback){
let script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
// For class based components
componentDidMount() {
loadScript("scriptUrl", callback());
}
// For functional components
useEffect(() => {
loadScript("scriptUrl", callback());
}, [])
Source: add third-party js library to Create React App

Load recaptcha script dynamically vue

I want to dynamically load the script such as recaptcha because I only want to load inside Register.Vue / login.Vue component
<script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer>
</script>
If I place the script tag inside my Vue files I get this error:
- Templates should only be responsible for mapping the state to the UI. Avoid
placing tags with side-effects in your templates, such as <script>, as they will
not be parsed.
How do I potentially fix this problem?
In your login Vue page, add :
methods: {
// create
createRecaptcha () {
let script = document.createElement('script')
script.setAttribute('async', '')
script.setAttribute('defer', '')
script.id = 'recaptchaScript'
script.src = 'https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit'
script.onload = function () {
document.getElementsByTagName('head')[0].appendChild(script)
}
},
// remove
removeRecaptcha () {
document.getElementById('recaptchaScript').remove()
}
},
// your code ...
mounted () {
this.createRecaptcha()
},
beforeDestroy () {
this.removeRecaptcha()
}

Categories

Resources