Fix- Navigating to a screen outside of current Navigation Stack in React Native and Expo

Before updating ReactNative version to 0.81.5 from 0.77 the following code to navigate bewteen screens stopped working.

const { navigation } = props;
navigation.navigate(
  'Gift Codes'
)

The Gift Code screen was a part of different navigation stack named BottomTabNavigator and rendered parallel to the RedeemScreenStack from one of the screens of which I needed to navigate to “Gift Codes” screen which one of the screens in BottomTabNavigator stack. So to repeat the code above worked before but not after the upgrade.

In order to make it work, the following code was incorporated instead.

First of all import “CommonActions” and “useNavigation” component libraries of react-navigation/native library.

import { CommonActions, useNavigation } from '@react-navigation/native';

In the main functional component extract “useNavigation” for handling navigation actions.

const OrderPlacedScreen = () => {
  ......
  const navigation = useNavigation();
  ......
}

And finally call reset method of “CommonActions” functional class.

navigation.dispatch(
  CommonActions.reset({
    index: 0,
    routes: [{ 
      name: 'BottomTabNavigator',
      state: {
        routes: [
          {
            name: 'Gift Codes',
          }
        ]
      }
    }],
  })
)

Remember that using reset method we inside deeply nested routes and screens. We just need to repeat using the name and state in a nested manner.

I hope it helps someone.

Leave a Reply