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.
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?
react-navigation = ^1.0.0-beta.11 react-native = 0.44.0
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;
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With