0

We are working on React Native project. In that, We are showing tabbar in that and also sidebar too. So, for that side bar we added react-navigation library. But, In, Android, If user tap on that device's back button, if the drawer is opens, We have to close it.

So, We are adding addListener in componentDidMount() and removing it in componentWillUnmount().

But, The issue is, If I switch to another tab and come back to previous tab, And if we tap on device back button, The back button handler not calling due to listener is removed.

Is there any alternative which method will call always once we switched to previous screen.

We know, componentDidMount only will call once while launching time of that screen.

We know we can call render method, But, We are expecting to call it in with good practice.

And is there any way to make it global way instead of writing call the classes closing drawer.

Code:

componentDidMount() {
    BackHandler.addEventListener('backTapped', this.backButtonTap);
}
  componentWillUnmount() {
    BackHandler.removeEventListener('backTapped', this.backButtonTap);

}

 backButtonTap = () => {
   navigation.dispatch(DrawerActions.closeDrawer());
}

Any suggestions?

  • Changing the active tab should change the parent component's state, so you can listen for that change and reattach the listener, maybe? –  Apr 09 '19 at 09:53
  • Thanks so much for your quick reply @ChrisG, But, I am looking for any other default method or some property would be there to call this as with good practice. And is there any way to make it global way instead of writing call the classes closing drawer. – Anilkumar iOS - ReactNative Apr 09 '19 at 09:56

1 Answers1

1

I would suggest to use react-navigation's own Navigation Lifecycle listener, so you can also handle different back button behaviour on different page.

componentDidMount() {
    this.willFocusListener = navigation.addListener('willFocus', () => {
      BackHandler.addEventListener('backTapped', this.backButtonTap);
    });
    this.willBlurListener = navigation.addListener('willBlur', () => {
      BackHandler.removeEventListener('backTapped', this.backButtonTap);
    });
}

componentWillUnmount() {
    this.willFocusListener.remove();
    this.willBlurListener.remove();
}

Then NavigationEvents component could be helpfull too

wicky
  • 948
  • 6
  • 13