Call External JavaScript Function from React Typescript Components

Call external Javascript function from react typescript components

You can extend the Window interface like this:

interface Window {
test(): void;
}

When you are doing this within a module, you need to ensure it is the global Window interface you are extending:

declare global {
interface Window {
test(): void;
}
}

This provides the type implementation to the compiler.

Call external Javascript function from react components

In index.html

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

In your component

componentWillMount() {
window.test();
}

React Typescript, Call a function from external script

You can add it to the Window interface from inside a TypeScript module (ts or tsx) like this:

declare global {
interface Window {
manipulator: () => void;
}
}

Or you can create a global global.d.ts (name doesn't matter, only that it's inside your source directory), containing this:

declare interface Window {
manipulator: () => void;
}

Be aware that this makes the function available everywhere, also before the script is initialized.

Importing Javascript in React TypeScript component

I was able to solve it by keeping it as a script tag import in the HTML file then calling the functions I needed from the window window.$pop.render(params). I had to add declare global { interface Window { $pop:any;}} so TypeScript knew to expect $pop in window. I got this by cominbing these solutions: How do I use external script that I add to react JS? and TypeScript error: Property 'X' does not exist on type 'Window' .

External JS file callback using component class property in typescript

Fixed by using the () => {} instead of function callback and using _this = this:

declare var external: any;

@Component({
selector: 'payment-form',
templateUrl: './payment-form.component.html'
})
export class PaymentFormComponent implements AfterViewInit {

testVar = 'test';
external = external;

constructor() {
}

ngAfterViewInit(): void {
const _this = this;
this.external.init({
'error-callback': (errors) => {
console.error(errors);
console.log(_this.testVar);
_this.showErrors();
},
'debug': true
});
}
}


Related Topics



Leave a reply



Submit