React Navigation 5 Authentication Flow

In this blog we are going to see how we can integrate Authentication Flow in React Navigation 5. I am going to cover all the points which is necessary in the integration. Because I personally face many problems regarding this implementation. I am using Context API for this. So before starting the blog we should know about Context API.

What is Context API in React?

The React Context API is a way for a React app to effectively produce global variables that can be passed around. This is the alternative to “prop drilling” or moving props from grandparent to child to parent, and so on. 

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

Now we will see how we can use Context API for the Authentication Flow in React Navigation5.

Step 1: Create a React Native Project using the command

npx react-native init ProjectName

Step 2: Install the necessary packages for the navigation.

npm install @react-navigation/[email protected]^5.x

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

Step 3: We are going to create two screens Login screen and Dashboard Screen and a file for managing the Context API. So when the user just click the login button we are going to navigate user to the Dashboard. So please find the project structure first. After that we are going to write the normal code for Login and Dashboard.

As you can see we have created a file Context.js inside the Component folder. So first see the Context.js file.

Context.js

import React from 'react';

export const UserContext = React.createContext({
    isLoggedIn: false,
    login: () => { },
    logout: () => { }
});

As we have use the method createContext for creating the Context Object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree. So we are going to use this context in our main file App.js and we are going to create the provider component through which we just wrap our app component so that we can use this context value throughout the App.

Login.js

import React,{useContext,useEffect} from 'react';
import {
  Text,
  TouchableOpacity,
} from 'react-native';
import {UserContext} from '../../Components/Context'

const Login = ()=>{
    const userContext = useContext(UserContext);

    return(
        <TouchableOpacity style={{justifyContent:'center',alignItems:'center'}} onPress={()=>{}}>
            <Text style={{fontSize:16,fontWeight:'bold'}}>Login Screen</Text>
        </TouchableOpacity>
    )
}

export default Login;

Dashboard.js

import React,{useContext} from 'react';
import {
  Text,
  TouchableOpacity
} from 'react-native';
import {UserContext} from '../../Components/Context'


const Dashboard = ()=>{
    const userContext = useContext(UserContext);

    return(
        <TouchableOpacity style={{justifyContent:'center',alignItems:'center'}} onPress={()=>{}}>
            <Text style={{fontSize:16,fontWeight:'bold'}}>Dashboard Screen</Text>
        </TouchableOpacity>
    )
}

export default Dashboard;

Step 4: Now we are going to create a navigation file where we write our navigation related codes through that user can navigate from one screen to another.

Router.js

import React,{useContext} from 'react';
import LoginScreen from '../Screens/LoginScreen/Login';
import DashboardScreen from '../Screens/DashboardScreen/Dashboard';
import { NavigationContainer } from '@react-navigation/native';
import {UserContext} from '../Components/Context'
const AppNavigator = props => {
    const userContext = useContext(UserContext);
    const isAuth = userContext.isLoggedIn;
    return (
        <NavigationContainer>
            { !isAuth && <LoginScreen/>}
            { isAuth && <DashboardScreen/>}
        </NavigationContainer>
    );
};
export default AppNavigator;

As you can see we have used the context value isLoggedIn in our router file so that we can manage the switch navigation using this. If the user is logged in then the value of this isLoggedIn changed to true other it will be false. And according to that user can navigate from login to dashboard and vice versa. So we are going to manage these functionality in the login screen and app.js file.

App.js

import React, {useState} from 'react';
import RootNavigator from './App/Navigation/Router';
import {UserContext} from './App/Components/Context';

const App = () => {
  const [loggedIn, setLoggedIn] = useState(false);
  const login = () => {
    setLoggedIn(true);
  };
  const logout = () => {
    setLoggedIn(false);
  };

  return (
    <UserContext.Provider
      value={{isLoggedIn: loggedIn, login: login, logout: logout}}>
      <RootNavigator />
    </UserContext.Provider>
  );
};

export default App;

In this file we have created two method login and logout and in that method we have just managed the states and passed the value of that state to the child component which is wrapped by the UserContext Provider. RootNavigator is our component through which we manage our navigation. So the ContextAPI values are present in all the components or screens present in the RootNavigator.

So when we just call the login method of UserContext in our LoginScreen then the value of isLoggedIn value changes accordingly and that isLoggedIn value is used in our Router.js file to switch between two different screens. We have also use AsyncStorage to manage the token value to be store in the device local storage. So for that we need to install the AsyncStoragein our project.

npm i @react-native-async-storage/async-storage

Updated Login Screen

import React,{useContext,useEffect} from 'react';
import {
  Text,
  TouchableOpacity,
} from 'react-native';
import {UserContext} from '../../Components/Context'
import AsyncStorage from '@react-native-async-storage/async-storage';
const Login = ()=>{
    const userContext = useContext(UserContext);
    const login=()=>{
        AsyncStorage.setItem('Token','Data');
        userContext.login()
    }
    useEffect(() => {
        async function getToken() {
            const token = await AsyncStorage.getItem('Token');
            if(token)
            {
                userContext.login()
            }
        }
        getToken();
     }, [])
    return(
        <TouchableOpacity style={{justifyContent:'center',alignItems:'center'}} onPress={()=>{login()}}>
            <Text style={{fontSize:16,fontWeight:'bold'}}>Login Screen</Text>
        </TouchableOpacity>
    )
}

export default Login;

So in the Login screen when the screens loads for first time we will check the value of token if it exists we directly navigate the user to Dashboard screen by calling the ContextAPI method. And if there is no token present in that case user will be in the login screen and if the user clicks the login button then the ContextAPI Login method is called and isLoggedIn value changed and user navigate to Dashboard screen.

Updated Dashboard Screen

import React,{useContext} from 'react';
import {
  Text,
  TouchableOpacity
} from 'react-native';
import {UserContext} from '../../Components/Context'
import AsyncStorage from '@react-native-async-storage/async-storage';

const Dashboard = ()=>{
    const userContext = useContext(UserContext);
    const logout=()=>{
        AsyncStorage.removeItem('Token');
        userContext.logout()
    }
    return(
        <TouchableOpacity style={{justifyContent:'center',alignItems:'center'}} onPress={()=>{logout()}}>
            <Text style={{fontSize:16,fontWeight:'bold'}}>Dashboard Screen</Text>
        </TouchableOpacity>
    )
}

export default Dashboard;

In the Dashboard screen we have created a logout method where we just clear the token value and call the ContextAPI logout method.

By using this functionality we can easily use ContextAPI for Authentication Flow in React Navigation 5. If there multiple number of screen you can use Stack Navigation function and use accordingly.

0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x