'Restrict app from going back via react-native-webview (React Native)
I have developed a website using react and now I've been trying to use this via webview in react native.
Problem: When I am using back button, the app exits.
Reason:
- In my React Website I am using Link {from react-router dom} so the navigation is not being added in history.
- In React Native since
onNavigationStateChangeuses history, navState.canGoBack() is returning false.
What can I include in this else block in handleBackButton so that app doesn't exit?
import React, { Component } from "react";
import { SafeAreaView, Platform, StatusBar } from "react-native";
import { BackHandler } from "react-native";
import { WebView } from "react-native-webview";
export default class Marketplace extends Component {
constructor(props) {
super(props);
this.state = {
canGoBack: false,
}
}
WEBVIEW_REF = React.createRef();
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton);
}
handleBackButton = () => {
if (this.state.canGoBack) {
this.WEBVIEW_REF.current.goBack();
return true;
} else {
console.log("Else block");
// what to add here to restrict the app to exit
}
};
onNavigationStateChange = (navState) => {
console.log("navState", navState.canGoBack);
this.setState({
canGoBack: navState.canGoBack,
});
};
render() {
return (
<SafeAreaView
style={{
flex: 1,
paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
}}
>
<WebView
source={{
uri: "http://localhost:3000/",
}}
ref={this.WEBVIEW_REF}
onNavigationStateChange={this.onNavigationStateChange}
/>
</SafeAreaView>
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
