react-nativenavigationstack-navigator

Changing navigation animation direction in react-native?


I'm currently working on a mobile application written in react-native. This project has a number of different screens all of which are configured with createStackNavigator.

I need to be able to change the animation direction on the fly. I could be navigating to the same page on different parts of the app but require different animations. (by animation I means the direction the current screen exits the view)

I am aware options can be passed to the screen when defined to set the navigation direction. This is unfortunately no use to me as the animation may change from page to page.

Example screen declaration from my project (names have been sanitised):

<NavigationContainer ref={navigationRef}>
  <Stack.Navigator initialRouteName={initialRoute}>
     <Stack.Screen name="screen1" component={screen1} options={{headerShown: false, gestureEnabled: false}} />
     <Stack.Screen name="screen2" component={screen2} options={{headerShown: false, gestureEnabled: false}} />
     <Stack.Screen name="screen3" component={screen3} options={{headerShown: false, gestureEnabled: false}} />
     <Stack.Screen name="screen4" component={screen4} options={{headerShown: false, gestureEnabled: false}} />
  </Stack.Navigator>
</NavigationContainer>

Example navigation reset:

  navigation.reset({
    index: 0,
    routes: [{ name: "screen1", params: { param1: 'paramStrData' } }]
  });

Example navigation replace:

navigation.replace('screen2', { param1: 'param1StrData'})

Ideally, I'd like to be able to pass a navigation animation direction to the replace or reset functions.

Is this at all possible?

Thanks again in advance.


Solution

  • Both answers above contributed to a solution in some way.

    My understanding of the navigation stack was a little flawed at this time. We can't dynamically change the animation type - i.e. swipe left or right.

    The animation type is selected based on where the new screen is on the navigation stack or not. If already on the stack, the current screen will exit to the right and the new (previous) screen will enter from the left - this is to simulate going back.

    If the new screen is not on the navigation stack, the new screen will enter from the right to simulate adding a new screen to the navigation stack.

    naviagation.navigate('screenName', {param1: 'p1', param2: 'p2'})
    

    navigate needs to be used opposed to replace to make this work.

    Hope this helps someone at some point as this was something I struggled to understand for some time.