How to reset state in react navigation v5?

Viewed 6425

How can I use navigation.reset prop to reset (or create a new navigation history) current navigation state and create a new one.

I have such router structure (see example below) and I want to navigate from Screen 3 to the Screen4. After navigation, I should be able to press back button to navigate back in history. In my case it should be the default screen (Screen5) of Tab2.

NativeStackNavigator
  Screen1
     BottomTabNavigator
       Tab1
       Tab2
         NativeStackNavigator
            Screen5 (default) <- navigate here after back button was pressed
            Screen4 <- to this route
       Tab3
       Tab4
  Screen2
  Screen3 <- from this route

Currently, I was able to achieve this by following code. But, unfortunately the back button doesn't exist inside the header.

props.navigation.reset({
  index: 1,
  routes: [
    {
      name: 'Screen1',
      params: {
        screen: 'Tab2',
      },
    },
    {
      name: 'Screen1',
      params: {
        screen: 'Tab2',
        params: { screen: 'Screen4' },
      },
    },
  ],
})

Additional info:

package.json

"@react-navigation/bottom-tabs": "^5.5.1",
"@react-navigation/native": "^5.5.0",
"react-native-screens": "~2.2.0",

Update #1
I would rather expect to keep history after resetting a state.

Update #2
I was able to accomplish this task by using the following example. Thank to @satya164.

navigation.navigate('Screen1', {
  screen: 'Tab2',
  params: {
    initial: false,
    screen: 'Screen4',
  },
});
1 Answers

You can specify child navigator's state in state property of route:

navigation.reset({
  index: 1,
  routes: [
    {
      name: 'Screen1',
      state: {
        routes: [{ name: 'Tab2' }],
      },
    },
    {
      name: 'Screen1',
      state: {
        routes: [
          {
            name: 'Tab2',
            state: {
              routes: [{ name: 'Screen5' }, { name: 'Screen4' }]
            },
          },
        ],
      },
    },
  ],
})

But this is going to reset your navigation state with completely new state, unmounting and remounting some screens. You can keep the old routes like shown in dispatch docs but it only applies to current navigator, not child navigator.

Here, it seems like you just want navigate, not reset. If Screen5 is the initialRouteName in your native stack, then:

navigation.navigate('Screen1', {
  screen: 'Tab2',
  params: {
    initial: false,
    screen: 'Screen4',
  },
});
Related