0

I have this code where I have the back button on android devices disabled for one screen of my app, when I change to another screen the back button gets enabled again in componentWillUnmount, however if I move to another screen by pressing the button below it does not run componentWillUnmount so I decided to add the removeEventListener to the onPress aswell. For some reason this does not work, if I push the button it does navigate to my other screen, however it does not remove the event listener.

Also: Yes I have also tried placing the code in the onPress in it's own function, this made no difference however, it still switched screen but did not re-enable my back button.

componentWillMount()
{
  BackAndroid.addEventListener('hardwareBackPress', () => {return true});
}

componentWillUnmount()
{
  BackAndroid.removeEventListener('hardwareBackPress');
}

render(){
  return(
    <Button 
      style={styles.button} 
      onPress={() => {BackAndroid.removeEventListener('hardwareBackPress'); this.props.navigation.navigate('home');}}>
    </Button>
  );
}
random1234
  • 777
  • 3
  • 17
  • 41

1 Answers1

2

The signature of BackAndroid.addEventListener and BackAndroid.removeEventListener are not the same. Hence, hardwareBackPress has not been removed in ComponentWillUnmount. Please try something like this:

constructor() {
   this._onBack = this._onBack.bind(this)
}
_onBack() {
   return true;
}

componentWillMount()
{
  BackAndroid.addEventListener('hardwareBackPress', this._onBack);
}

componentWillUnmount()
{
  BackAndroid.removeEventListener('hardwareBackPress', this._onBack);
}
Cao Minh Vu
  • 1,900
  • 1
  • 16
  • 21
  • Thank you, it worked, however I have a question, what do you mean that it wasn't being removed in `ComponentWillUnmount`? If it wasn't being removed, why did it work whenever I switched screen through the menu, but not when I clicked the button? – random1234 Apr 17 '18 at 11:35
  • I mean the event 'hardwareBackPress" is not removed. It is still controlled by this function: () => {return true}. Hence, the back button will not work on other screens. – Cao Minh Vu Apr 18 '18 at 01:37
  • Suppose, i want to removeEventListener when navigating to next screen of its own stack. That time, removeEventListener is not working. Anyone please tell me what i have to do! – Johncy Feb 21 '19 at 06:51
  • I have the same issue and when I try your solution I get an error: undefined is not an object (evaluating '_this._onBack') – zedArt Mar 02 '20 at 14:38