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?
CodePudding user response:
you can't just create a new ref and use that in your anotherComponent
. If you want to display the webview
in your anotherComponent
, you need to import it and return is as part of the anotherComponent
.
CodePudding user response:
There are 2 ways to do this, with and without using name ref
for the reference property.
- Without using
ref
prop 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 usingforwardRef
feature 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>
);
}