2
I’m developing a website in React and I need to use an external Javascript lib (I don’t have his npm package), so I have a link to import on the site. At first I thought of importing it into HTML even with the tag script
, but I could not access any of the functions, giving only the error 'funcao' is not defined
.
After that I went after a way to import only where I will need and I came across the code below that actually created the tag script
, but once again I did not succeed to invoke the function.
const loadScript = async () => {
const script = document.createElement("script");
script.type = "text/javascript";
script.id = "ID do script";
script.src = `URL DA LIB`;
script.async = false;
document.body.appendChild(script);
setLoaded(true)
return () => {
document.body.removeChild(script);
};
}
I’m calling this function up using the useEffect
and even put a state to only invoke the function after the loaded
for true
, but similarly, I keep getting an error when compiling because the function does not exist.
I can use the functions by the browser console, which I understand indicates that the import is working correctly, so my question is how should I call this function? I’ve tried to funcao()
, window.funcao()
and window['funcao']
and nothing, always having the same mistake of 'funcao' is not defined
.
Is the library an ES6 module or is it a normal script? If it is an ES6 module, why are you including the script with the type
text/javascript
? If it is a normal script, why are you trying to import? Anyway, include the tagscript
within areact hook
, although it is not prohibited or impossible, it is, most of the time, bad sign.– Vander Santos
I believe it is normal script. I am importing by following the instructions of the Pagseguro API for creating transparent checkout. I even found a package that does this checkout, but I will need this checkout for recurring payment and for standard cart, which this package does not support. For reference, follow the link of the documentation of the secure page: https://dev.pagseguro.uol.com.br/reference/checkout-transparent#transparent-library-javascript
– buenojc
I tried to reproduce your problem and answered your question. The only detail I did not consider and I suppose you did not pass one
async function
to theuseEffect
- I assumed that, because in those cases theReact
complains and shows an error message on the console. As you did not mention this message, anyway, if the answer does not solve your problem, add more details.– Vander Santos