Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the Android Hardware Back Button from functioning in react-navigation for react-native?

I am developing a trivia game, I am using react-navigation to handle navigation, I have 3 components, (newGame, Questions, Results ) I don't want the user to go back to the questions from the results page if the no. of questions has been exhausted, however, pressing the back button ( Android Hardware ) is taking him back to the questions. I then tried to handle the hardware back button like so:

componentWillMount() {
      this.props.gameState(true);
      BackHandler.addEventListener('hardwareBackPress', () => {
        if (this.props.gamePlaying) { // Currently set to true. I will set it to false again on NewGame Page.
          this.props.navigation.navigate('NewGame');
        }
      });
    }

However, this is taking the user to the NewGame screen but immediately, it is bouncing back to the results page as it is firing the NAVIGATION/BACK as well immediately in the NewGame page. Which is again taking it back to the results page.

Possible fix?

I want to stop the the back button to fire after I have landed in the NewGame component page. Is there a way to do it?

My Environment

react-navigation = ^1.0.0-beta.11 react-native = 0.44.0

like image 577
Sankalp Singha Avatar asked Jun 27 '17 07:06

Sankalp Singha


1 Answers

You need to return true to indicate you have handled the back button yourself as you can see in the docs.

if one subscription returns true then subscriptions registered earlier will not be called

Your code should look like this:

componentWillMount() {
    this.props.gameState(true);
    BackHandler.addEventListener('hardwareBackPress', () => {
        if (this.props.gamePlaying) {
            this.props.navigation.navigate('NewGame');
            return true; // This will prevent the regular handling of the back button
        }

        return false;
    });
}
like image 62
Moti Azu Avatar answered Oct 13 '22 03:10

Moti Azu