noa-dev
noa-dev

Reputation: 3641

Call normal javascript function from another document in a react component function

I am trying to call a normal javascript function inside of a react component function.

The script tags are nested in the footer as following :

<script src="NORMAL JAVASCRIPT STUFF"></script> // function test(){};
<script src="REACT STUFF"></script>

So the javascript file with the function that I need is being read earlier. So the function should be available in the whole document.

Now when I try to call the function within some react component function like that:

....,
someFunction: function(){
test();
},...

I get Uncaught ReferenceError: test is not defined

Does anyone know how to access normal functions inside of react?

Upvotes: 1

Views: 3540

Answers (2)

Joe P
Joe P

Reputation: 444

Based on what you've posted my guess is that you have test defined within a function. If a variable or function is defined within another function, it is scoped to that function, and only available there. It would not be globally available. You would need to move the test definition to outside of any function within "NORMAL JAVASCRIPT STUFF".

e.g. if you have

function xyz {
    function test() {}
}()

you need to change to

function xyz() {}
function test() {}

OR

you can explicitly assign the function to the global scope

function xyz() {
    window.test = function() {}
}

As a general rule, you want to limit what you have in the global javascript "window" object so as to avoid conflicts.

Upvotes: 2

Michael Parker
Michael Parker

Reputation: 12966

That function would belong to the window object, so you would need to call window.test(); instead.

See here:

https://jsfiddle.net/7dzdp9rw/

Upvotes: 7

Related Questions