Vishal Pachpande
Vishal Pachpande

Reputation: 540

I am using Backhander in react native with react-native-router-flux but its reacting on all screens where I want to make it work for screen specific

I am using Backhander in react native with react-native-router-flux but it's reacting on all screens where I want to make it work for screen-specific, but when I am trying to get the current route name in the onBackPress method, it's giving me first screen name in router name.

componentDidMount() {
   BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount() {
   BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress = () => {
   alert(this.props.navigation.state.routeName)
}

Upvotes: 1

Views: 247

Answers (2)

Pradnya Choudhari
Pradnya Choudhari

Reputation: 394

If you want backHandler to act differently for specific screen then you can use Actions.currentScene in your onBackPress function :

onBackPress = () => {
       if(Actions.currentScene === 'SceneKey'){
             return true;
       }
       Actions.pop();
       return true;
    }

Upvotes: 1

Alexander Kuttig
Alexander Kuttig

Reputation: 426

First of all - BackHandlers in React Native are global and not screen specific. But you can achieve your wanted behavior.

Some background

With BackHandler.addEventListener you push an event listener on a Stack of event listeners, with BackHandler.removeEventListener you remove the given listener from the Stack. When the BackButton is pressed, the top listener from the stack is called and the code is executed. Then the next listener is called and so on. This stops when the first listener returns true.

For your specific problem

  • You should ensure that you add an event listener on the page you want it to (like you are doing in your code example)
  • You should ensure that your event listener returns true
  • You should ensure that your listener gets removed when unmounting the view (like you do)

Now you BackHandler should work for the view you have implemented it in (lets call it view1). But you have to think about all the other views. Especially when you are pushing views on top of view1. Ether you can implement an "onFocus" and "onBlur" method for view1 and use this methods instead of componentDidMount and componentWillUnmount for adding and removing event listeners, or you have to add event listeners for the back handler for all views that are pushed on top of view1.

Hope that helps :-)

Source: https://facebook.github.io/react-native/docs/backhandler

Upvotes: 1

Related Questions