Google Login Using React Native

Description

 
In this article we will learn how to implement Google Login in React Native. I will explain this step by step. I assume that you have basic knowledge of React js. So let’s start our implementation.
 
Output
 
 
Prerequisite
  • Getting Started React Native: https://reactnative.dev/docs/getting-started
  • Required Plugin: https://www.npmjs.com/package/react-native-google-signin
To create fa Futter app follow the following steps,
 
Step 1
 
First step is to create a new React Native app. Following is the command for that:
  1. npx react-native init GPlusLogin  
  2. cd GPlusLogin  
Step 2
 
Then, run the app. I am running the project on my device using the following command:
  1. react-native run-android  
So now we are having a default app run on our device.
 
Step 3
 
Now, we will install a plugin to implement Google login in React native app. Following is the plugin installation command for that:
  1. npm i react-native-google-signin  
Step 4
 
Follow the documentation for Android and ios project setup.
 
Step 5
 
Once Android setup is done by following Step 4, you have google-service.json file. Place the generated configuration file (google-services.json) into <YOUR_PROJECT_ROOT>/android/app
 
Step 6
 
Update android/build.gradle with
  1. buildscript {  
  2. ...  
  3.     dependencies {  
  4.         ...  
  5.         classpath('com.google.gms:google-services:4.3.3'// ADD THIS  
  6.     }  
  7. ...  
  8. }  
Step 7
 
Update android/app/build.gradle with
  1. android {  
  2.    ...  
  3.    signingConfigs {  
  4.         release { // CHANGE FROM debug TO release  
  5.            storeFile file('debug.keystore')  
  6.            storePassword 'android'  
  7.            keyAlias 'androiddebugkey'  
  8.            keyPassword 'android'  
  9.        }  
  10.    }  
  11. }  
  12. dependencies {  
  13.    ...  
  14. }  
  15. apply plugin: 'com.android.application' // ADD THIS  
  16. apply plugin: 'com.google.gms.google-services’ // ADD THIS  
Step 8
 
Great -- you are done with setup. Now we will programmatically implement Google login, silent login and logout. So below is the programming for that. Open App.js and place it into it.
  1. import React, { useEffect, useState } from 'react';  
  2. import {  
  3.  StyleSheet,  
  4.  View,  
  5.  StatusBar,  
  6.  TouchableOpacity,  
  7.  Text,  
  8.  Image  
  9. } from 'react-native';  
  10. import { GoogleSignin, GoogleSigninButton, statusCodes } from 'react-native-google-signin';  
  11. GoogleSignin.configure({  
  12.  webClientId: '--------------.apps.googleusercontent.com'// client ID of type WEB for your server (needed to verify user ID and offline access)  
  13.  });  
  14. const App: () => React$Node = () => {  
  15.  const [isLoggedIn, setIsLoggedIn] = useState(false)  
  16.  const [userInfo, setUserInfo] = useState(null)  
  17.  useEffect(() => {  
  18.    getCurrentUserInfo();  
  19.  }, []);  
  20.  const getCurrentUserInfo = async () => {  
  21.    try {  
  22.      const userInfo = await GoogleSignin.signInSilently();  
  23.      console.log(userInfo);  
  24.      setIsLoggedIn(true);  
  25.      setUserInfo(userInfo);  
  26.    } catch (error) {  
  27.      if (error.code === statusCodes.SIGN_IN_REQUIRED) {  
  28.        // user has not signed in yet  
  29.      } else {  
  30.        // some other error  
  31.      }  
  32.    }  
  33.  };  
  34.   
  35.  const _signIn = async () => {  
  36.    try {  
  37.      await GoogleSignin.hasPlayServices();  
  38.      const userInfo = await GoogleSignin.signIn();  
  39.      console.log(userInfo);  
  40.      setIsLoggedIn(true);  
  41.      setUserInfo(userInfo);  
  42.    } catch (error) {  
  43.      console.log(error);  
  44.      if (error.code === statusCodes.SIGN_IN_CANCELLED) {  
  45.        // user cancelled the login flow  
  46.      } else if (error.code === statusCodes.IN_PROGRESS) {  
  47.        // operation (e.g. sign in) is in progress already  
  48.      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {  
  49.        // play services not available or outdated  
  50.      } else {  
  51.        // some other error happened  
  52.      }  
  53.    }  
  54.  };  
  55.   
  56.  const _signOut = async () => {  
  57.    try {  
  58.      await GoogleSignin.revokeAccess();  
  59.      await GoogleSignin.signOut();  
  60.      setIsLoggedIn(false);  
  61.    } catch (error) {  
  62.      console.error(error);  
  63.    }  
  64.  }  
  65.  return (  
  66.    <>  
  67.      <StatusBar barStyle="dark-content" />  
  68.      <View style={styles.container} >  
  69.        {  
  70.          !isLoggedIn ?  
  71.            <GoogleSigninButton  
  72.              style={{ width: 192, height: 48 }}  
  73.              size={GoogleSigninButton.Size.Wide}  
  74.              color={GoogleSigninButton.Color.Dark}  
  75.              onPress={_signIn}  
  76.            /> :  
  77.            <>  
  78.              <Text>Email: {userInfo ? userInfo.user.email : ""}</Text>  
  79.              <Text>Name: {userInfo ? userInfo.user.name : ""}</Text>  
  80.              <TouchableOpacity style={styles.signOutBtn} onPress={_signOut}>  
  81.                <Text style={styles.signOutBtnText}>Signout</Text>  
  82.              </TouchableOpacity>  
  83.            </>  
  84.        }  
  85.      </View>  
  86.    </>  
  87.  );  
  88. };  
  89.   
  90. const styles = StyleSheet.create({  
  91.  container: { flex: 1, justifyContent: "center", alignItems: "center" },  
  92.  signOutBtn: {  
  93.    backgroundColor: "#556688",  
  94.    padding: 10,  
  95.    borderRadius: 10  
  96.  },  
  97.  signOutBtnText: {  
  98.    color: "white"  
  99.  }  
  100. });  
  101.   
  102. export default App;  
Step 9
 
Great you are done with it. Now run and check the app.
 

Conclusion

 
In this article we have learned how to integrate Google Login using React Native.


Similar Articles