I am trying to add going back on webview when the android backbutton was pressed and I still couldn\'t manage to make it work.
This is my code:
If you are looking for a functional component
solution.
Note: canGoBack state is not required for performing back operation, it's just to save the current state, you can safely remove it if you want
import React, { useState, useEffect, useRef } from "react"
import { BackHandler, Platform } from "react-native"
import { SafeAreaView } from "react-navigation"
import { WebView } from "react-native-webview"
const Webview = () => {
const webView = useRef(null);
const [canGoBack, setCanGoBack] = useState(false);
useEffect(() => {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', HandleBackPressed);
return () => {
BackHandler.removeEventListener('hardwareBackPress', HandleBackPressed);
}
}
}, []); // INITIALIZE ONLY ONCE
const HandleBackPressed = () => {
if (webView.current) {
webView.current.goBack();
return true; // PREVENT DEFAULT BEHAVIOUR (EXITING THE APP)
}
return false;
}
return (
"
}}
onNavigationStateChange={navState => setCanGoBack(navState.canGoBack)}
/>
)
}
export default Webview;