BackHandler not working properly React Native

Viewed 1114

I am trying to go back when the user presses back button on Android.

I have added listener to the screen and it's receiving event when in the remotely debug mode. But it's not working properly when I don't do debug remotely. It's really weird.

I am gonna attach code snippets that I have written.

//Navigator
const BoardNavigator = StackNavigator({
    Board: { screen: Board }
});

//Board Component
class Board extends Component {
    componentWillMount () {
        BackHandler.addEventListener('hardwareBackPress', this._onBackPressed);
    }

    componentWillUnmount () {
        BackHandler.removeEventListener('hardwareBackPress', this._onBackPressed);
    }

    _onBackPressed () {
        console.log('backPress');
        goBack(this.props.navigation);
        return true;
    }

    onNext() {
        this.props.navigation.navigate("Board", {content: ...});
    }
}

Additional Info : This BoardNavigator is the nested one of the rootNavigator(StackNavigator).

react : '16.0.0-alpha.12'

react-native : "0.47.2"

1 Answers

I've actually used backhandler like below for controlling back button to close the application just with 2 press immediately.

componentDidMount() {
this._backPress = 0;

BackHandler.addEventListener('backPress', () => {
  setTimeout(() => {
    this._backPress = 0;
  }, 3000);

  this._backPress += 1;
  if (this._backPress <= 1) {
    ToastAndroid.showWithGravity(strings.BACK_BUTTON_ALERT, ToastAndroid.SHORT, ToastAndroid.CENTER);
    return true;
  }
  return false;
});
Related