mr.b
mr.b

Reputation: 2708

Call external Javascript function from react components

Im not sure if this has been asked before or anybody has encountered the same issue on reactjs. So the scenario is like this, I have an index.html file that includes some javascript. Now on my react component, I have a condition that will render only if the condition is true. This means that initially when my page loaded the component has not been rendered yet. When I toggle a button this is where that component gets rendered. That child component needs to call a javascript method that was included on my index.html. How should I do this?

Any help is greatly appreciated.

Upvotes: 43

Views: 112095

Answers (5)

Made in Moon
Made in Moon

Reputation: 2464

In index.html

<script type="text/javascript">
  function test(){
    alert('Function from index.html');
  }
</script>

In your component

componentWillMount() {
  window.test();
}

2022 Typescript edit:

Create a file global.d.ts like so (doc):

interface Window {
  test: () => void;
}

Upvotes: 93

Douglas C
Douglas C

Reputation: 161

for typescript users, try this:

declare global {
    interface Window {
        externalMethod: (params: any) => void;
    }
}

then you would be able to call it like this in your react component

window.externalMethod(params)

Upvotes: 1

AdamVanBuskirk
AdamVanBuskirk

Reputation: 519

You can attached your method to the global window object and than use it like that in your component:

<button onClick={this.howItWorks} type="button" className='btn'>How it Works</button>

howItWorks = () => {
  window.HowItWorksVideo();
}

Upvotes: 0

Dmytro Bondarenko
Dmytro Bondarenko

Reputation: 1022

Try this solution to call global functions from React with TypeScript enabled:

Either in index.html or some_site.js

function pass_function(){
  alert('42');
}

Then, from your react component:

window["pass_function"]();

And, of course, you can pass a parameter:

//react
window["passp"]("react ts");

//js
function passp(someval) {
  alert(`passes parameter: ${someval}`);
}

Upvotes: 16

gor181
gor181

Reputation: 2068

So either you define the method on global scope (aka window). And then you can use it from any methods, being React or not.

Or you can switch to module based paradigm and use require/import to get the module and use the function.

For bigger projects the latter is better as it's scales, while if you need a demo or POC you can certainly hook all to global scope and it will work.

More information about modules is at: http://exploringjs.com/es6/ch_modules.html

Upvotes: 3

Related Questions