Created
July 26, 2020 07:20
-
-
Save Subhojit1992/5fa70c36df04327115742bd353ae7291 to your computer and use it in GitHub Desktop.
React native run website as app with back button press to go back previous URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { WebView } from 'react-native-webview'; | |
import { | |
View, | |
BackHandler, | |
Platform, | |
StyleSheet, | |
StatusBar, | |
} from 'react-native'; | |
export default class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
} | |
} | |
webView = { | |
canGoBack: false, | |
ref: null, | |
} | |
onAndroidBackPress = () => { | |
if (this.webView.canGoBack && this.webView.ref) { | |
this.webView.ref.goBack(); | |
return true; | |
} | |
return false; | |
} | |
componentWillMount() { | |
if (Platform.OS === 'android') { | |
BackHandler.addEventListener('hardwareBackPress', this.onAndroidBackPress); | |
} | |
} | |
componentWillUnmount() { | |
if (Platform.OS === 'android') { | |
BackHandler.removeEventListener('hardwareBackPress'); | |
} | |
} | |
render(){ | |
return ( | |
<> | |
<StatusBar backgroundColor="#f48024" /> | |
<View style={{flex:1}}> | |
<WebView | |
source={{ uri: '' }} | |
ref={(webView) => { this.webView.ref = webView; }} | |
onNavigationStateChange={(navState) => { this.webView.canGoBack = navState.canGoBack; }} | |
style={{flex: 1}} | |
/> | |
</View> | |
</> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
backgroundColor: '#fff', | |
alignItems: 'center', | |
justifyContent: 'center', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment