Issue
I have a basic WebView:
const WebViewComponent = () => {
function sendDataToWebView() {
webviewRef.current.postMessage('Hello world');
}
const webviewRef = useRef();
return (
<SafeAreaView>
<WebView
ref={webviewRef}
source={{
uri: 'https://www.google.com/',
}}
/>
</SafeAreaView>
);
}
Calling sendDataToWebView() works in this component since i have the reference. (useRef()).
But in another component:
const anotherComponent = () => {
const webviewRef = useRef();
webviewRef.current.postMessage('Hello world');
}
webviewRef is undefined.
How can i access my WebView from another component?
Solution
There are 2 ways to do this, with and without using name ref for the reference property.
- Without using
refprop name, i.e. use any other name.
const WebViewComponent = ({ webviewRef }) => {
return (
<WebView
ref={webviewRef}
source={{ uri: 'https://www.google.com/' }}
/>
);
};
const AnotherComponent = () => {
const webviewRef = useRef();
useEffect(() => {
const test = () => {
const run = "window.alert('haha');";
webviewRef.current?.injectJavaScript(run);
};
setTimeout(test, 3000);
}, []);
return (
<SafeAreaView>
<WebViewComponent
webviewRef={webviewRef}
// ....
/>
</SafeAreaView>
);
}
- Using
ref. This is possible usingforwardReffeature of React. You can read more about it here.
const WebViewComponent = React.forwardRef((props, ref) => {
return (
<WebView
ref={ref}
source={{ uri: 'https://www.google.com/' }}
/>
);
});
const AnotherComponent = () => {
const webviewRef = useRef();
// .....
return (
<SafeAreaView>
<WebViewComponent
ref={webviewRef}
// ....
/>
</SafeAreaView>
);
}
Answered By - vinayr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.