'Why Navigation.goBack() not working properly?

I am using following way to create navigation system

StackNavigator -> DrawerNavigator -> (Screen A, Screen B, Screen C)

Screen A is initial Route

Screen A to Screen B Using

this.props.navigation.navigate("Screen B")  //Working Fine

Screen B to Screen C Using

this.props.navigation.navigate("Screen C")  //Working Fine

In Screen C

this.props.navigation.goBack() //Not Working

But

this.props.navigation.goBack(null) //It's going to Screen A instead of Screen B

What's wrong here.

Please help me Thank you.



Solution 1:[1]

As you didn't show the navigation structure of the drawer, I don't know how the 3 screens are put inside of it. I'm assuming they are 3 different drawerScreens

This happens because you are using a DrawerNavigation, that doesn't create a history of screens when you navigate around it.

To solve this you have to change the navigation structure to something like:

DrawerNavigation => StackNavigator => Screen A, B, C

Solution 2:[2]

As the answer above is, the drawer navigators are not in the stack, so you can't tell the path of your journey.

the key property for goBack() is a dynamically created string, created by react-navigation whenever navigate to a new route.

These stack keys are stored in this.props.navigation.state

NOTE: Use .goBack(null) if your goal is to return to any place without specifying a closing target.

Like this example, you can add to the stack.

Example

const Drawers = createDrawerNavigator(
  {
    A: {
      screen: HomeScreen
    },
   ...
  },
  {
    initialRouteName: "A"
  }
);

const RootStack = createStackNavigator(
  {
    Drawers: {
      screen: Drawers
    },
    otherStack: {
      screen: otherStack
    },
    ....

Solution 3:[3]

You can specify backBehavior="history" inside Drawer.Navigator and it shouldn't move you to the initial root on goBack anymore :)

Example:

 <Drawer.Navigator
      backBehavior="history"
    >
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 hong developer
Solution 3 Agnieszka Jankowy