Disable navigating back to Login/Signup screen in react navigation 5.x

Viewed 3830

I am using React Navigation 5

My structure is like this:

ROOT (STACK)
  |-- LoginStack (STACK)
  |   |-- Login (SCREEN) -> when successful navigate to "Mainapp_stack"
  |   +-- Register (SCREEN) -> after registration, navigate to "Mainapp_stack"
  |
  +-- Mainapp_stack (STACK)
      |-- Dashboard (SCREEN)
      |-- MyProfile (SCREEN)

It is ok by checking usertoken I can able to navigate to the main appstack but,

At the very first time in the process of Login/Registration how to prevent user navigating back after successful Login/Registration in react-navigation 5.x

App.js

    <NavigationContainer>
      <Stack.Navigator>
          {this.state.token_available ? 
            <Stack.Screen 
              name="Mainapp_stack" 
              component={Mainapp_stack}
              options={{headerShown: false}}
            />
          :
          <>
            <Stack.Screen 
              name="TeacherLogin" 
              component={TeacherLogin}
            />
            <Stack.Screen 
              name="Info" 
              component={Info}
            />
            <Stack.Screen 
              name="Mainapp_stack" 
              component={Mainapp_stack}
            />
          </>
          }
        </Stack.Navigator>
    </NavigationContainer>

Mainapp_stack.js

     <Stack.Navigator initialRouteName='Dashboard'>
        <Stack.Screen 
          name="Dashboard" 
          component={Dashboard}
          // options={{headerShown: true}}
        />
      </Stack.Navigator>

Now when I complete log in/Registration, I do not want to navigate back if I press the hardware back button. My variable token_available is in App.js and I am not using redux.

So, How can I solve it?

1 Answers

in your main screen use this code:

import { useFocusEffect } from "@react-navigation/native";
useFocusEffect(
React.useCallback(() => {
  const onBackPress = () => {
    Alert.alert("Hold on!", "Are you sure you want to Exit?", [
      {
        text: "Cancel",
        onPress: () => null,
        style: "cancel"
      },
      { text: "YES", onPress: () => BackHandler.exitApp() }
    ]);
    return true;
  };

  BackHandler.addEventListener("hardwareBackPress", onBackPress);

  return () =>
    BackHandler.removeEventListener("hardwareBackPress", onBackPress);

}, []));

read more here: React navigation documents

Related