Switch Navigator
The world’s latest technologies, policies, business-boosting strategies will be written here. Contact Morosoft

In this article, we will look into the Switch Navigator.

[ultimate_heading main_heading=”What is Switch Navigator and why we use it?” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

Switch Navigator is used to show one screen at the time depending on the state of the user. It is basically used to handle the exact behavior of authentication flow. For example, we want to show the user home screen and log out screen when logged in and want to show the registered screen or sign-in screen when log out.

[ultimate_heading main_heading=”Overview of project.” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

Our app is going to work like so…



When the user opens the app we’ll show them the LoggedOut layout so that they can log in or register them(in this app I am just asking the user to log in by pressing the login button). When a user login I am updating a status code 200 in mobile storage so that whenever he opens the app again we can check it whether he signed in already or not.

And when the user successfully logged in we replace the layout with LoggedIn layout. As a result, the user should not be able to go back to the login screen unless they are signed out.

[ultimate_heading main_heading=”Let’s implement Switch Navigator in our app:” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

If you are not familiar with react-navigation then you have to check my previous article.

From our app overview it’s clear that we need two layouts. As purpose of this article is just to show you the working of switch navigator so I will not be using any TabNavigator or DrawerNavigator.

We will be handling all our layouts in one file config/routes.js file. If you are not familiar with how to structure react native project than you can check out my this article.

We will be using AsyncStorage to check whether spelling mistakes user has signed in or not. We will be using a status code to check that.

createSwitchNavigator is finally used to check which layout has to render.

[ultimate_heading main_heading=”Let’s code for SignedOut Layout:” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]
import { createStackNavigator, createSwitchNavigator, createAppContainer, } from 'react-navigation'; import LoginScreen from '../screens/login'; import SignUp from '../screens/signUp';   const SignedOut = createStackNavigator( { Login: { screen: LoginScreen, }, SignUp: { screen: SignUp, }, }, { headerMode: 'none', }, );

We will be using this SignedOut layout in app entery point. So let’s edit out app/index.js file

import { SignedOut } from './config/routes.js'

class App extends React.Component {

render() {
return (
< SignedOut />
);
}
}

I will not code login or signUp screen here because it’s not part of this article.

[ultimate_heading main_heading=”Let’s code for SignedIn Layout:” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]
import HomeScreen from '../screens/home';

const SignedIn = createStackNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
  },
  {
    headerMode: 'none',
  },
);

Now let’s test it from our app’s entry point. In result we will see a home screen.

import { SignedOut, SignedIn } from './config/routes.js'

class App extends React.Component {

render() {
    return (

        < SignedIn />

    );
  }
}

As we have coded both layouts and also rendering signedout layout on app entrance. Now let’s code where we will check the state of a user. Let’s navigate to the login screen and add status code to our Storage on pressing the login button.




import { AsyncStorage } from 'react-native';

//handling a function when login button is pressed

  handleFormSubmission = () => {
    let x = true;
    AsyncStorage.setItem('isSignIn', '200');
    this.props.navigation.navigate('SignUp');
  };

Now in routes.js file let’s check whether the user is signed in or not. For that, we will use the componentWillMount life cycle.

By default let’s set the state of the user as logout.

this.state = {
      isLoggedIn: false,
    };

  componentWillMount = async () => {
    let signedIn = await AsyncStorage.getItem('isSignIn');
    if (signedIn == '200') this.setState({isLoggedIn: true});
  };

Now let’s code our createSwitchNavigator which will be responsible for rendering layout depending on the state.

const createRootNavigator = (signedIn = false) => {
  return createSwitchNavigator(
    {
      SignedIn: {
        screen: SignedIn,
      },
      SignedOut: {
        screen: SignedOut,
      },
    },
    {
      initialRouteName: signedIn ? 'SignedIn' : 'SignedOut'
    },

  );
};

[ultimate_heading main_heading=”Now let me explain how switch navigator works :” alignment=”left” main_heading_font_size=”desktop:24px;” main_heading_style=”font-weight:bold;” main_heading_margin=”margin-bottom:10px;”][/ultimate_heading]

We are passing two params to out createSwitchNavigator(RouteConfigs, SwitchNavigatorConfig).

You can see that I have defined two layouts and I am checking which initial route needs to be rendered based on signedIn arguments of the function.

Now we will use createAppContainer to wrap the root navigator

  render() {
    const AppContainer = createAppContainer(
      createRootNavigator(this.state.isLoggedIn),
    );
    return <AppContainer />;
  }

Let’s default export this and use it in our app entry point. This is how our routes.js file will look like at the end.

import React, {Component} from 'react';
import {AsyncStorage} from 'react-native';
import {
  createStackNavigator,
  createSwitchNavigator,
  createAppContainer,
} from 'react-navigation';

import LoginScreen from '../screens/login';
import SignUp from '../screens/signUp';
import HomeScreen from '../screens/home';

const SignedOut = createStackNavigator(
  {
    Login: {
      screen: LoginScreen,
    },
    SignUp: {
      screen: SignUp,
    },
  },
  {
    headerMode: 'none',
  },
);

const SignedIn = createStackNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
  },
  {
    headerMode: 'none',
  },
);

const createRootNavigator = (signedIn = false) => {
  return createSwitchNavigator(
    {
      SignedIn: {
        screen: SignedIn,
      },
      SignedOut: {
        screen: SignedOut,
      },
    },
    {
      initialRouteName: signedIn ? 'SignedIn' : 'SignedOut',
      headerMode: 'none',
      navigationOptions: {
        header: false,
        swipeEnabled: false,
        drawerLockMode: 'locked-closed',
        gesturesEnabled: false,
      },
    },
  );
};

class AppRoot extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: false,
    };
  }
  componentWillMount = async () => {
    let signedIn = await AsyncStorage.getItem('isSignIn');
    if (signedIn == '200') this.setState({isLoggedIn: true});
  };
  render() {
    const AppContainer = createAppContainer(
      createRootNavigator(this.state.isLoggedIn),
    );
    return <AppContainer />;
  }
}

export default AppRoot;

Now use this AppRoot in our app’s entry point.

import AppRoot from './config/routes';

  render() {
    return (
      <Provider store={store}>
        <AppRoot />
      </Provider>
    );
  }
}

Now our app will be working perfectly fine and will be giving us exactly the same experience as we was expecting.

To enhance your knowledge regarding advanced technologies tune to Morosoft tweaks https://www.mstweaks.com/.
If you want to be up to date with all what is happening in the world, Morosoft Tweaks is providing you all under one roof. We also aim to provide relevant information in a quick and sophisticated manner. Therefore you can contact us: info@morosoft.pk.

LEAVE A REPLY

Please enter your comment!
Please enter your name here