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

Stack.Navigator fade-transition between Stack.Screens in React-native?


How can I add a transition effect to Stacked Screes in React-native?

<NavigationContainer>
    <Stack.Navigator
        screenOptions={{
            headerShown: false,
        }}
    >
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Stocks" component={StocksScreen} />
    </Stack.Navigator>
</NavigationContainer>

Is there a default way to achieve a fadeIn / fadeOut effect?


Solution

  • The simplest way to achieve fade effect:

    const forFade = ({ current }) => ({
      cardStyle: {
        opacity: current.progress,
      },
    });
    

    If you want to apply fade effect for the entire navigator:

    <Stack.Navigator
       screenOptions={{
          headerShown: false,
          cardStyleInterpolator: forFade,
       }}>
       <Stack.Screen name="Home" component={HomeScreen} />
       <Stack.Screen name="Stocks" component={StocksScreen} />
    </Stack.Navigator>
    
    

    Also you can apply cardStyleInterpolator for single screen via setting options:

    <Stack.Screen 
      name="Home" 
      component={HomeScreen} 
      options={{ cardStyleInterpolator: forFade }}/>
    

    You can customize forFade function in order to achieve other effects, or also you can use some pre-made interpolators, as:

    • forHorizontalIOS
    • forVerticalIOS
    • forModalPresentationIOS
    • forFadeFromBottomAndroid
    • forRevealFromBottomAndroid
    import { CardStyleInterpolators } from '@react-navigation/stack';
    
    <Stack.Screen
      name="Profile"
      component={Profile}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forFadeFromBottomAndroid,
      }}
    />;
    

    More info here: https://reactnavigation.org/docs/stack-navigator/#animations