Asaf
Asaf

Reputation: 2168

Complex navigation in React Native using react-navigation and Redux

I have the following navigation structure in my React Native app:

StackNavigator configured with 3 routes:

  1. Splash screen (React Component)
  2. StackNavigator for my login flow
  3. DrawerNavigator for my core app screens.

The DrawerNavigator has some dynamic multiple routes, but also one static route which is another StackNavigator. Everything seems to be working as expected:

  1. The store is being updated accordingly.
  2. Navigation between screen works.
  3. Go back between screen works when configured within each component, with the following command:

    this.props.navigation.goBack();
    

My question is - is there a way for me to handle back button on Android globally? Currently when I click on the back button, nothing happens (due to the fact I'm using Redux). Should I handle the back button in each component or is there a way of doing it using Redux?

Upvotes: 1

Views: 586

Answers (1)

Tall Paul
Tall Paul

Reputation: 2450

A bit late, but there is a way to handle this with redux. In your index.js file where you create your store you can make export a class and add a componentWillMount call to handle dispatching a call to your redux actions. Just remember to import the actions you need above.

const store = configureStore();

export default class Index extends Component {
  componentWillMount = () => {
      BackHandler.addEventListener('hardwareBackPress', () => {
          const { nav: { routes } } = store.getState();
          const currentRouteName = routes[routes.length-1].routeName;

          if (currentRouteName === 'EditCoupleProfile') {
              store.dispatch(editCoupleActions.navigateBack())
          } else if ( currentRouteName === 'EditInterests' ) {
              store.dispatch(interestsActions.navigateBack())
          } else {
              store.dispatch(popFromStack());
          }
          return true;
      })
  };

  componentWillUnmount = () => {
      BackHandler.removeEventListener('hardwareBackPress');
  };

  render() {
      return (
          <Provider store={store}>
              <AppWithNavigation />
          </Provider>
      );
   }
}

Upvotes: 0

Related Questions