Saturday, December 23, 2017

react-native handling complex back button functionality

Leave a Comment

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.

2 Answers

Answers 1

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.

Answers 2

React-native has an api for handling hardware back actions on Android and AppleTV. You add your eventListender to the BackHandler component. Docs

If you are using react-navigation, you can place this event listener in the component that is rendering your stack. You can then find the screen in the stack that corresponds to your navigation state and call the leftButton onPress. Here is a rough example -

const _RootContainer = (props) => {   const navigation = addNavigationHelpers({     dispatch: props.dispatch,     state: props.nav,   })   BackHandler.addEventListener('hardwareBackPress', function() {   const route = navigation.state.routes[navigation.state.index]   const screen = stack[route].screen   const navOptions = screen.navigationOptions({navigation})       if (navOptions.headerLeft) {     navOptions.headerLeft.props.onPress()   }       return true;   });   return (<View style={{ flex: 1 }}>     <AppNavigator       navigation={navigation}     />   </View> )} 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment