Moving to a screen in a nested navigator React Navigation v5

30 Views Asked by At

Context

I saw lots of similar questions but no one was a valid answer to my problem. This is my navigator structure:

MainNavigator (mode="modal", headerMode="none")
 - TabNavigator
   - StackHomeNavigator
     - HomeScreen
     - DeadlineScreen
   - ...other tabs
 - StackSettings
   - ScreenSettings
   - UserInfoScreen
   - ConfigureMFA

Description

Usually if I want to navigate to ConfigureMFA I need to click on settings icon which loads the StackSettings and present it as a modal. Then I click on "Account Settings" which navigate to UserInfoScreen and then I click on "Configure MFA" which navigate to ConfigureMFA. The goal is to navigate from HomeScreen to ConfigureMFA. But I also want that, once I'm in ConfigureMFA screen I'm able to go back to UserInfoScreen and from there go back to ScreenSettings. So basically the navigate history has to be the same as a "manual" navigation.

Really important: the HomeScreen needs to be visible all the time as the StackSettings appears as a Modal (think of ModalPresentationIOS).

What I tried

I tried with CommonActions.reset as the documentation suggest. But the app has some strange behavior and flicker. And also I'm not interested on "resetting" my route but instead navigate.

What I came up

After some researches I came up with this code. And it works! But the documentation does not say nothing about put state as a navigation param.

navigation.navigate(AppNavigatorName.SETTINGS, {
  screen: ScreenKeys.configureMfa,
  state: {
    routes: [
      { name: ScreenKeys.settingsScreen },
      { name: ScreenKeys.userInfoScreen },
      { name: ScreenKeys.configureMfa }
    ]
  }
});

Question

Do you guys know why this code works?? Is there any other best practices?

1

There are 1 best solutions below

1
ko100v.d On

This probably works, which is surprising me, because you're overwriting the navigation state. I do not think it is recommended. The way you can solve this is by using navigation.reset

navigation.reset({
    index: 2,
    routes: [
        { name: ScreenKeys.settingsScreen },
        { name: ScreenKeys.userInfoScreen },
        { name: ScreenKeys.configureMfa }
    ],
});

This way react-navigation will reset and rebuild it's own state correctly and when you hit back from your Settings screen you should go back to Home