React Navigation: How to push two routes to the stack without flickering transition

Viewed 303

Hi I'm trying to use React Navigation to navigate directly from screen A to screen C whilst at the same time programmatically inserting screen B in between them so that when I use the Back button on screen C I end up in screen B rather than screen A. I've got it working using the following code

navigation.push('B')
navigation.push('C')

The only problem is that during the transition from A to C, screen B briefly flickers into view. I'd like to get rid of this flickering transition so that the it looks like a direct transition from A to C, whilst imperceptibly adding screen B in between them. Is there any way to do this?

I also tried using navigation.reset but had the same transition issue as when using navigation.push.

navigation.reset({
    index: 2,
    routes: [
      {name: 'A'},
      {name: 'B'},
      {name: 'C'},
    ],
  })
1 Answers

An alternative approach you could take is to directly navigate from A to C with

navigation.navigate('C');

and to define custom back buttons with custom back button behavior for screen B and C

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="A" component={A} />
        <Stack.Screen
          name="B"
          component={B}
          options={({navigation}) => ({
            headerLeft: props => (
              <HeaderBackButton
                onPress={() =>
                  navigation.reset({index: 0, routes: [{name: 'A'}]})
                }
              />
            ),
          })}
        />
        <Stack.Screen
          name="C"
          component={C}
          options={({navigation}) => ({
            headerLeft: props => (
              <HeaderBackButton onPress={() => navigation.navigate('B')} />
            ),
          })}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

In screen C the back button navigates to B and in screen B the back button resets the navigation state and navigates to screen A so the back button doesn't show up on screen A.

Related