Search code examples
react-navigationreact-navigation-stackreact-navigation-v5

How to specify custom transitions for specific routes, not screens (v5)


Question regarding react-navigation v5.

In previous versions, we were able to specify custom transition for specific routes, not screens, by doing the following inside a StackNavigator:

      transitionConfig: () => ({
         screenInterpolator: sceneProps => {
         const {scenes, scene} = sceneProps;
         const prevRoute = scenes[0].route.routeName === 'Route A'; 
         // If prev route is A, and then current route is B, then we do a specific transition
         if (prevRoute && scene.route.routeName === 'Route B') { 
          return StackViewStyleInterpolator.forVertical(sceneProps);
         }
         // Otherwise default to normal transition
         return StackViewStyleInterpolator.forHorizontal(sceneProps);
        },
      }),

Now, I'm trying to achieve the same for react-navigation v5. I know I'm able to specify a custom animation per screen by doing something like:

<Stack.Screen name="Route B" component={RouteB} options={{ cardStyleInterpolator: CardStyleInterpolators.forVerticalIOS }} />

The problem is that I don't want this transition applied every time it is navigated to RouteB, ONLY when the previous route is RouteA, I want this transition applied, just like the previous code block above.

Couldn't find any example in the docs so would appreciate some help in migrating the code over to v5.


Solution

  • Something like this should work:

    options={({ navigation, route }) => {
      const state = navigation.dangerouslyGetState();
      const index = state.routes.indexOf(route);
      const previousRoute = state.routes[index - 1];
    
      if (previousRoute?.name === 'RouteA') {
        return {
          cardStyleInterpolator: CardStyleInterpolators.forVerticalIOS,
          gestureDirection: 'vertical',
        };
      } else {
        return {};
      }
    }}