Diksha Mundhra
Diksha Mundhra

Reputation: 161

How to invoke a function written in html root script from a react component

How to invoke a function which is present at root html script from react component which is somewhere in children react-dom?

Upvotes: 1

Views: 1463

Answers (3)

shwetav
shwetav

Reputation: 69

You can create function in separate file and import that function in react component then call a function in component let's say on button click or if there are nested component then can pass as a prop.

Upvotes: 0

Vindhyachal Kumar
Vindhyachal Kumar

Reputation: 1794

Declare the function in child component as below

declare function NotifyWebView();

Then call the function from any method of child component

NotifyWebView();

Upvotes: 0

Muni Perez
Muni Perez

Reputation: 90

You can add the function to the window object.

root.html

window.NotifyWebView = function () { 
 // ...your code
}

index.tsx

componentDidMount() {
 window.NotifyWebView && window.NotifyWebView();
}

I see you are using Typescript, and it will complain that property "NotifyWebView" does not exist in the window object. Then you need to declare it. Add this at the end of the index.tsx file:

declare global {
 interface Window {
  NotifyWebView?(): void // Make it optional
 }
}

Upvotes: 5

Related Questions