To close a WebView in React Native, you can make use of the ‘react-native-webview’ library and its ‘react-native-webview’ component. The WebView component provides a method called ‘injectJavaScript’ which allows you to execute JavaScript code inside the WebView.
To close the WebView, you can inject JavaScript code that calls the ‘window.close()’ function. This function is commonly used to close browser windows and can also be used to close a WebView.
Here is an example that demonstrates how to close a WebView in React Native using the ‘react-native-webview’ library:
import React, { useRef } from 'react';
import { View, Button } from 'react-native';
import { WebView } from 'react-native-webview';
const App = () => {
const webViewRef = useRef(null);
const closeWebView = () => {
webViewRef.current.injectJavaScript("window.close();");
};
return (
<View style={{ flex: 1 }}>
<Button title="Close WebView" onPress={closeWebView} />
<WebView
ref={webViewRef}
source={{ uri: 'https://www.example.com' }}
/>
</View>
);
};
export default App;
In this example, we create a functional component called ‘App’ which contains a WebView and a button. The WebView is wrapped inside a ‘View’ component and we use the ‘react-native-webview’ library’s ‘WebView’ component.
We use the ‘useRef’ hook to create a reference to the WebView component. The reference is stored in the ‘webViewRef’ variable.
The ‘closeWebView’ function is called when the button is pressed. Inside this function, we call the ‘injectJavaScript’ method on the ‘webViewRef.current’ object. This method executes the JavaScript code ‘window.close()’ inside the WebView, which closes the WebView.
Finally, we render the button and the WebView component inside the ‘View’ component. The WebView component is configured with a source URL of ‘https://www.example.com’. You can replace this URL with your desired website URL or local file path.
Make sure to install the ‘react-native-webview’ library by running the following command:
npm install react-native-webview
Also, remember to link the library to the project by running the following command:
npx react-native link react-native-webview