How to make external javascript file work in ReactJs? - javascript

In a React project, my public.html file looks like this:
<head>
<link rel="stylesheet" href="some_stylesheet_file.css">
</head>
<body>
<div id="root"></div>
<script src="function.js"></script>
</body>
All the components of the project load inside the "root" div.
The "function.js" file is an external javascript file from a theme.
In one of the React components, I have an input field:
<input type="text" name="userName" id="userName" />
Now, inside "componentDidMount()" of that component, if I write
console.log(document.getElementByID("userName"))
it shows the "userName" field correctly in the console. But if I do the same thing in the "function.js" file, the output is null, which indicates the external javascript file is not working properly. I am not sure how to make the external javascript file work so that I can use the properties of the theme. Can anyone help?

We use the DOM method to load external JS in our ReactJS app.
For example, https://api.mesibo.com/mesibo.js is an external JS library provided by mesibo, we load it as following
const externalJS = "https://api.mesibo.com/mesibo.js";
const script = document.createElement("script");
script.src = externalJS;
document.body.appendChild(script);

Related

I would like to use a <script> in my Angular component, how do I do that ? (TypeScript, Angular12)

This is the code that I would like to use in my Angular component:
<form action="https://www.meu-site.com/processar-pagamento" method="POST"> <script
src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
data-public-key="ENV_PUBLIC_KEY"
data-transaction-amount="100.00"></script></form>
If you have to load the script from remote site you can add it to your index.html file, like you would do in a regular html site.
index.html
<!-- get script from 3rd party site -->
<script
src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
data-public-key="ENV_PUBLIC_KEY"
data-transaction-amount="100.00">
</script>
Then, to use the the script in your component, you need to manually declare the exported variables / functions to avoid TS compilation errors
** formComponent.ts**
declare let web-tokenize-checkout: any; //declare the name of the global object you got from the script you added
//use your script functionality, That part is really depends on how the script you imported works
web-tokenize-checkout.doWhatEverYouNeed(....);

Running a JavaScript as an external script in Laravel

I have a blade code like this:
<input type='text' id="input1">
<div >
<h3 id="showData"> Data will be shown here </h3>
</div>
<script>
var input=document.getElementById('input1').value;
document.getElementById('showData').innerHTML=input;
</script>
What I want is to write the script part in a separate file (say called externalScript.js) and call it here in the blade file.
Also, I have a doubt about it. If I do that, since the script is run from an external file, how will it fetch the id values like input1 or showData ?
Write a new file called: externalScript1.js
Add the script tag, best in the head or foot part of your code.
<script src="{{ asset('externalScript1.js') }}" defer></script>
(the asset helper gets the path to the public folder, https://laravel.com/docs/8.x/helpers#method-asset)
In the end everything will load from one page, ergo the elements are found, so you won't have a problem.
Just add js file in laravel resources directory, link to webpack and compile more info.
when it comes to executing the script, attach it at the end of the page (before </body>) or wait for the page to be loaded document.addEventListener('DOMContentLoaded', function() {})
Attach the js file in the main wrapper, not in the nested blade element

unable to add inline and external javascripts into vue js file?

I have html file which has 3 script tags. I want to put these script tags in my vue.js file
my html file
<html>
<body>
<script type="text/javascript">
mxBasePath = "../editors/pure";
</script>
<script type="text/javascript" src="../editors/pure/js/mxClient.js"></script>
<script src="../editors/dist/main.js"></script>
</body>
</html>
So i want to add the 3 script tags seen in the above html to my vue js file.So for this i have
tried to create the script tags manually in the mounted function of the vue file as seen below-
my vue js file
<template>
<div id="geApp">
</div>
</template>
<script>
const client = '../editors/pure/js/mxClient.js'
const mains = '../editors/dist/main.js'
mounted () {
var a = document.body.getElementsById("geApp")
let basePath = document.createElement('script')
basePath.innerText = 'mxBasePath = "../editors/pure"'
basePath.async = true
a.appendChild(basePath)
let recaptchaScript = document.createElement('script')
recaptchaScript.setAttribute('src', './pure/js/mxClient.js')
recaptchaScript.async = true
a.appendChild(recaptchaScript)
let processes = document.createElement('script')
processes.setAttribute('src','./dist/main.js')
processes.async = true
a.appendChild(processes)
},
.....
.....
</script>
Unfortunately iam getting an error saying http://localhost/editors/dist/main.js net::ERR_ABORTED 404 (Not Found) from main.js file.So how do i load these scripts correctly in my vue js file?
If files that you are trying to add are some libraries/plugins that doesn't support import or require for some reason only then you try to do the way you are adding the file to DOM:
Anyhow, If you are sure and don't care about webpack processing your .js files in anyways, then keep your files in ./public/assets/js/ folder, then just do:
<script src="./assets/js/your-file.js"></script>
Check this "How to add external JS scripts to VueJS Components" or search it in stackoverflow search box. Hope you will get the answer.

Why I can't type any letter if I separate the .js file?

Actually I was trying to get the concept of the module pattern. Here I have simple code which I used to type directly on the page. It was fine until I tried to separate the actual code from the HTML file and kept only a single line of code on the main HTML file:
<body>
<script type='text/javascript' src='module.js'>
// module.JS file was here ....
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
</body>
File module.JS
var module = (function() {
return {
show:function(keyCode){
document.body.innerHTML+=(String.fromCharCode(keyCode));
}
};
})();
You'll need to have two <script> elements for this.
Use one to "import" your external module and another for the script you want to embed directly on the page:
<script type='text/javascript' src='module.js'></script>
<script type='text/javascript'>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>
For more information, you can check out this MDN documentation page. Here is an excerpt talking about the src attribute (emphasis added):
This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. Script elements with an src attribute specified should not have a script embedded within its tags.
A script block referring to an external JavaScript source should be separate and any script inside of it does not get executed. So you need two separate script blocks one for the external JavaScript file and the other for your script.
<script src='module.js'></script>
<script>
document.body.addEventListener('keypress',function(e){module.show(e.keyCode)});
</script>

jquery script on html file

I'm using Bottle to make a simple web form and want to set the Selectize.js jquery plugin to a field so the user can set several values to that same field.
Inside my form tag I have the following code:
<label>
<span>Links :</span>
<input type="text" id="input-tags" name="links">
</label>
<script>
$('#input-tags').selectize({
persist: false,
createOnBlur: true,
create: true
});
</script>
And the following .js and .css inside the head tag:
<link href="/selectize.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="/selectize.js"></script>
To deal with static files I have the following route in my .py script:
#get('/<filename:re:.*\.js>')
def javascripts(filename):
return static_file(filename, root='static/js')
#get('/<filename:re:.*\.css>')
def stylesheets(filename):
return static_file(filename, root='static/css')
My route to deal with static files seems to be working properly 'cause I've tested it with other jquery plugin that does not use explicit code within the html file.
On this one, the problem seems to be on the explicit script code bellow the label tag. I found some articles about dealing with JSON but couldn't make it work (I also don't know if that is the right way to go).
Well, my best option was to put that explicit javascript into a new javascript file and add its path to the html like:
<script type="text/javascript" src="/<script_path_here>"></script>
That way my functions that handles the static files on the .py would do their job.

Categories

Resources