Q:

number of elements in react navigation stack

I want to check number of elements in my react navigation stack. if there was only one screen left and user press back button, application show them a message to exit the app. I had to use BackHandler in all of my screens because I hadn't had found a property which could show elements in stack.
this is my routes
const route1= {
    screen1,
    screen2
};

const route2= {
        screen3,
    screen4
};

export const stack1= createStackNavigator(route1);
export const stack2= createStackNavigator(route2);

export default {stack1, stack2};

this is my navigator
createNavigator = (routeName, params) => {
        this.navigator = createAppContainer(createSwitchNavigator(routes, { initialRouteName: routeName, initialRouteParams: params }));
    }

A:

As you are using react-navigation using createStackNavigator you could add the backHandler control only inside your initialRouteName screen, but you'll need to add an eventListener to check if the screen you are watching is actually the one that's focused, else it would trigger also in your other screens
If this is not the case, to check the length of your stack, inside your screen you can simply check it using your navigation prop:
handleBackPress=()=>{
   if(this.props.navigation.state.routes.length===1){
      //do what you need
     return true
   }
   else {
   this.props.navigation.pop(1)
   return true
   }
}

