Skip to content

Instantly share code, notes, and snippets.

@yoovanr
Created May 1, 2020 17:24
Show Gist options
  • Save yoovanr/e3659b07d573ae6b302b106fd2c29e47 to your computer and use it in GitHub Desktop.
Save yoovanr/e3659b07d573ae6b302b106fd2c29e47 to your computer and use it in GitHub Desktop.
[React Native] Custom WebView Component Example
// We use useImperativeHandle for having ability to call methods from parent component.
// We use onMessage method from WebView for triggering needed states from any web apps.
import React, { forwardRef, useImperativeHandle, useRef, memo } from 'react'
import { WebView } from 'react-native-webview'
const WebViewLink = forwardRef(({ onMessage }, ref) => {
const webviewRef = useRef()
useImperativeHandle(ref, () => ({
injectJavaScript (jsToInject) {
setTimeout(() => {
if (webviewRef && webviewRef.current) {
webviewRef.current.injectJavaScript(jsToInject)
}
}, 1000)
}
}))
return (
<WebView
ref={webviewRef}
source={{ uri: gameUrl }}
useWebKit={true}
originWhitelist={['*']}
javaScriptEnabled={true}
onMessage={(event) => onMessage(event)}
/>
)
})
export default memo(WebViewLink)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment