How to override React Native Back button

In this React Native source code example, the source code below illustrate how to override React Native Back button.

You can copy and adopt this source code example to your React Native project without reinventing the wheels.

import React, {Component} from 'react';
import {BackHandler, StyleSheet, Text, View,Alert, TouchableOpacity} from 'react-native';

export default class App extends Component {
  componentDidMount(){
    this.backButton = BackHandler.addEventListener('hardwareBackPress', () =>{
      Alert.alert(
         'Confirm Exit',
         'Do you want to quit',
         [
           {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
           {text: 'OK', onPress: () => BackHandler.exitApp()},
         ],
      );
      return true;
      });
  }
  componentWillUnmount(){
  this.backButton.remove();
  }
  render() {
    return (
      <View style={styles.container}>
          <Text>Press the Back Button !</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment