Search code examples
react-nativereact-navigationreact-navigation-stack

Reset StackNavigator from within the Component


BROAD PROBLEM (for individuals searching for the same solution):

I have an app with a switch-based StackNavigator ("MainStack"). I would like to reset MainStack as {index: 1, routes: [{name: 'Home', name: 'NestedStack'}]}, and I would like to call this from within the MainStack component (see below)

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        {
           anon ?
           <Stack.Screen name="Auth" component={AuthScreen} />
           <Stack.Screen name="MainStack" component={MainStackScreen} />
        }
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const MainStack = createStackNavigator();

function MainStackScreen({navigation, route}) {

  
  *** An event occurs here ***
  *** And I'd like to respond to the event with a navigation.reset() ***

  return (
    <MainStack.Navigator>
      <MainStack.Screen name="Home" component={Home} />
      <MainStack.Screen name="NestedStack" component={NestedStackScreen} />
    </MainStack.Navigator>
  );
}

I have tried several different combinations of navigation.dispatch({...CommonActions.reset({}), target}), producing different errors from the screen not existing to issues with screens.options.

I would also greatly appreciate advice on how to specify which screen to start with for NestedStack... would this just be {name: 'NestedStack', screen: 'NestedScreen'}??

SPECIFIC USE-CASE: What I am really trying to achieve is Linking. I have users opening links when the app is closed (which I am accessing via Linking.getInitialURL) and from Camera screens within the app (which I am listening to via Linking.addEventListener). I have placed both of these in the MainStack component to intercept links as the app switches from the auth flow and as a QR code is scanned within the app.

I have to listen to changes in the MainStackScreen route, then set a variable isNavigatorMounted to true once the route is fully mounted, and then that triggers my check for Linking.getInitialURL.

Please address the Broad Question for general StackOverflow users, but if this is a terribly inefficient method, please let me know.


Solution

  • This answer was provided https://discord.com/channels/102860784329052160/288388742929055765/770038660220715028

    You do not need CommonActions or anything. Simply apply the following to the StackNavigator's navigation object:

    navigation.reset({
        routes: [{ name: 'Home' }, { name: 'NestedStack' }],
    });