nwales
nwales

Reputation: 3561

React-Navigation with redux - Back button in StackNavigator nested within TabNavigator triggers back action in both navigators

I have react-navigation setup with redux. My app consists of a parent TabBarNavigator with a login and content screen. The content Screen is itself a Stack Navigator that contains the main nav for the app. All other aspects of the redux and navigators work as expected, but the default back button on the StackNavigator also triggers it's parent TabBarNavigator to go back.

Is this expected behavior? I notice that if I define headerLeft in navigationOptions like this, it works as expected:

static navigationOptions = ({ navigation }) => {
    return {
      headerLeft: (
        <Button transparent onPress={() => { navigation.goBack(); }}><Text>Back</Text></Button>
      )
    };
  };

Cam anyone explain what causes this? Is there a way to make the default stackNavigator back button work with redux?

Upvotes: 11

Views: 1257

Answers (3)

Julien Malige
Julien Malige

Reputation: 3475

In my case the issue was a little more complex because I use the react Navigation Redux Integration.

My back action is well a dispatch of a "back" action but, in my reducer, I missed the second parameter of the getStateForAction method (the state).

getStateForAction(action, state)

https://reactnavigation.org/docs/routers/api#getStateForAction-action-state

So, in my navigation redux, it works with this back reducer:

export const back = (state) => AppNavigator.router.getStateForAction(NavigationActions.back(), state)

With this back action, a back from a nested navigator is not reseting the main navigator.

Upvotes: 0

J.K.Rai
J.K.Rai

Reputation: 104

You can do one thing on onPress event, before call the goBack() you have to dispatch your action for that particular redux:

static navigationOptions = ({ navigation }) => {
return {
  headerLeft: (
    <Button 
        transparent 
        onPress={() => { 
          <ACTION_DISPATCH>
          navigation.goBack(); 
        }}>
        <Text>Back</Text>
   </Button>
  )
};};

Upvotes: 1

jughosta
jughosta

Reputation: 121

Maybe dispatching an action will work better:

    onPress={() => {
      navigation.dispatch(NavigationActions.navigate({
        routeName: '<screen name here>'
      }));
    }}

Upvotes: 1

Related Questions