switchNavigator with react-navigation 5

singhspk picture singhspk · Feb 25, 2020 · Viewed 10.3k times · Source

With react-navigation 4, I was able to import and use switchNavigator from "react-navigation" package.

import {
  createAppContainer,
  createSwitchNavigator,
  createStackNavigator
} from "react-navigation";

import MainTabNavigator from "./MainTabNavigator";
import LoginScreen from "../screens/LoginScreen";
import AuthLoadingScreen from "../screens/AuthLoadingScreen";

export default createAppContainer(
  createSwitchNavigator(
    {
      App: MainTabNavigator,
      Auth: AuthLoadingScreen,
      Login: createStackNavigator({ Login: LoginScreen })
    },

    {
      initialRouteName: "Auth"
    }
  )
);

With react-navigation 5, I don't see the createSwitchNavigator in the package anymore. The documentation isn't helpful either. Is the use now not recommended? My use case is to show login screen before user is logged in and switch to the app after user logs in. React-navigation has given an example of authentication flow but is it possible to use switchNavigator - which seems much simpler.

Answer

mleister picture mleister · Feb 25, 2020

The switchNavigator was removed because you can do the exact same stuff now with the help of rendering components conditionally.

import React from 'react';
import {useSelector} from "react-redux";
import {NavigationContainer} from "@react-navigation/native";

import { AuthNavigator, MyCustomNavigator } from "./MyCustomNavigator";

const AppNavigator = props => {
    const isAuth = useSelector(state => !!state.auth.access_token);

    return (
        <NavigationContainer>
            { isAuth && <MyCustomNavigator/>}
            { !isAuth && <AuthNavigator/>}
        </NavigationContainer>
    );
};
export default AppNavigator;

The lines inside the NavigationContainer fully replace the old switch navigator.