Reputation: 161
How to invoke a function which is present at root html script from react component which is somewhere in children react-dom?
root.html
<html>
<head>
<script type="text/javascript">
function NotifyWebView()
{
window.external.notify('Text');
}
</script>
</head>
<body>
<div id='root'></div>
</body>
</html>
index.tsx
componentDidMount{
//How to access and invoke NotifyWebView() ??
}
Upvotes: 1
Views: 1463
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
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
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