Skip to content

Instantly share code, notes, and snippets.

@Subhojit1992
Created July 26, 2020 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Subhojit1992/5fa70c36df04327115742bd353ae7291 to your computer and use it in GitHub Desktop.
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
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