I would like to know the recommended way(if there is one) to handle the back button in react-native when dealing with the android platform.
I know I can register listeners per screen but due to how navigation works there is no clear flow for binding or unbinding event listeners when navigating.
So far I have two ideas.
1) I can register one single listener and withing the handler make decisions based on my redux store. That means that if I have a screen where I have a popup that I want to close with the back button I have to expose it to the store. Essentially anything in my app that I want to be affected by a back button has to be connected to the store. Messy
2) I can register a listener per screen. From what I said earlier there are no reliable lifecycle hooks available to handle this so it will have to be manual on my end i.e I should always know what action will navigate to a new screen and unbind the listener on the particular screen before navigating.
That solves half the problem though. When navigating back to a screen it should rebind it's listener. Not sure how to do that except messing around with componentWillRecieveProps and the others. Still seems messy.
react-navigation
handles basic back button functionality for you without any work.
If you want some custom handling you can try react-navigation-addons library it will give you 2 events to listen to: focus
and blur
so you can register/unregister back button listeners when these events happen.
It is strategy 2) from your question, you can use this instead of missing lifecycle hooks. But be careful with this library it's an experiment, so read the note before using it. It would look something like this:
class Screen extends Component {
handleBack = () => {
...
}
screenFocus = () => {
// add back button listener or any other code you want to execute on screen focus
BackHandler.addEventListener('hardwareBackPress', this.handleBack);
}
screenBlur = () => {
// remove back button listener or add any other code you want to execute on screen blur
BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
}
componentDidMount() {
this.props.navigation.addListener('focus', this.screenFocus);
this.props.navigation.addListener('blur', this.screenBlur);
}
componentWillUnmount() {
this.props.navigation.removeListener('focus', this.screenFocus);
this.props.navigation.removeListener('blur', this.screenBlur);
}
...
}
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