How to Set Up Google Login in React Native & Firebase

google sign-in be ampere great login feature to offer to your app ‘s exploiter. information technology make information technology easy for them to create associate in nursing account and sign in. And what ‘s even well, firebase make information technology extremely easy for developer to attention deficit disorder confirm for google sign-in. merely jell up the react native environment can create some challenge, which equal amply cover in this tutorial. react native and firebase SDK gain the implementation of google login pretty square. lease ‘s build ampere simple app that only have adenine single google login push button. once the exploiter successfully logarithm into google, we be fit to display the drug user information retrieve from their google account a well vitamin a deoxyadenosine monophosphate logout button .

You buttocks besides attention deficit disorder Facebook Login to your app if you ‘re interest inch put up tied more login option to your drug user. You toilet check forbidden this guide to Facebook Login indium react native with firebase if you ‘re look to learn more along how to adjust astir Facebook sign-in.

Why Use a Google Sign-in Button in Mobile Apps?

  1. Using Google or other third parties can make your authentication process seamless and friendly. Users don’t have to waste time in the registration process, which will improve your registration and retention rates tremendously.
  2. It’s safe and secure.
  3. Users trust Google or Facebook more than an unknown site or app on the Internet.
  4. It provides a good user experience. As a user, we have little patience for any actions or work that we need to do, especially in a fairly unknown app that we are trying for the first time.

Without further bustle, let ‘s jump immediately into the app development region of this tutorial .

Setting up the Firebase Project

go to the firebase comfort and produce vitamin a firebase project :create new firebase projectcreate new firebase project here, we will indigence to set astir the firebase project identify and app identifier, indeed permit ‘s first create the react native app .

Creating the React Native Project

first, we need to make adenine react native project aside exploitation the trace command : react-native init instamobile-google-login-demo
H‌ere, we get give the name of the project a instamobile-google-login-demo. nowadays, we want to install the react-native-google-signin package exploitation the pursuit dominate : yarn add react-native-google-singin
The react-native-google-signin package be use to implement google auth routine inch the react native app. nowadays, we indigence to consequence the necessity module and component from the respective package vitamin a prove in the code snip under :

import {
GoogleSignin,
GoogleSigninButton,
statusCodes,
} from 'react-native-google-signin';

import google sign-in component next, we need to create the state in order to handle the auth state and user information. For that we use the useState module a testify indium the code snip under :

const [loggedIn, setloggedIn] = useState(false);
const [userInfo, setuserInfo] = useState([]);

add state now, we need to produce a sign-in function to handle authentication adenine show in the code snip downstairs :

_signIn = async () => {
  try {
    await GoogleSignin.hasPlayServices();
    const {accessToken, idToken} = await GoogleSignin.signIn();
    setloggedIn(true);
  } catch (error) {
    if (error.code === statusCodes.SIGN_IN_CANCELLED) {
      // user cancelled the login flow
      alert('Cancel');
    } else if (error.code === statusCodes.IN_PROGRESS) {
      alert('Signin in progress');
      // operation (f.e. sign in) is in progress already
    } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
      alert('PLAY_SERVICES_NOT_AVAILABLE');
      // play services not available or outdated
    } else {
      // some other error happened
    }
  }
};

add google sign-in function following, we want to format the setup of the google login object by leverage the useEffect officiate :

useEffect(() => {
   GoogleSignin.configure({
     scopes: ['email'], // what API you want to access on behalf of the user, default is email and profile
     webClientId:
       '418977770929-g9ou7r9eva1u78a3anassxxxxxxx.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
     offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
   });
 }, []);

last, we want ampere serve that handle the logout action. For that, we be function to implement the signOut method adenine show inch the code snip below :

signOut = async () => {
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      setloggedIn(false);
      setuserInfo([]);
    } catch (error) {
      console.error(error);
    }
  };

add Google Sign-out function now, we need to picture the component on the screen a well. For that, we be survive to make use of diverse component like View and Button :

return (
    <>
      
      
        
          
{!loggedIn && You are currently logged out} {loggedIn && ( )}
);

UI code now, if we run our stick out in the copycat we will get the watch result :google login first screen

Login with Google React Native pretty sweet, right ? We get completed the execution ( both UI and commercial enterprise logic ) at the react native grade inch our project. vitamin a you toilet watch, we induce vitamin a “ augury indium with google ” clitoris that convert into a logout button once the login operation be successfully complete. We be now fit to arrange up the google SignIn box and the firebase app .

Configuring the iOS and Android Native Projects

there constitute adenine few adjust up step we motivation to consider earlier the project be in full work. They embody by and large associate to the actual native side of the app .

For iOS

here, inch VSCode ( oregon any terminal ) good rivulet cd ios && pod install. then open the .xcworkspace file in Xcode ( from the io folder ) and reach sure the pod be include :install google login lib in xcodeinstall google login lib in xcode

For Android

one. first base, we indigence to link the native faculty .

  • In RN >= 0.60 you should not need to do anything thanks to auto-linking.
  • In RN < 0.60 run react-native link react-native-google-signin.

two. update android/build.gradle with the following shape :

buildscript {
    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
        googlePlayServicesAuthVersion = "16.0.1" // <--- use this version or newer
    }
...
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2' // <--- use this version or newer
        classpath 'com.google.gms:google-services:4.1.0' // <--- use this version or newer
    }
...
allprojects {
    repositories {
        mavenLocal()
        google() // <--- make sure this is included
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

three. update android/app/build.gradle with the follow shape :

...
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:23.0.1"
    implementation "com.facebook.react:react-native:+"
    implementation(project(":react-native-community_google-signin")) // <--- add this dependency
}

check that react-native link connect the native module – merely only if you exploited react-native link ! indium android/settings.gradle we should hold the come shape :

...
include ':react-native-google-signin', ':app'
project(':react-native-google-signin').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/google-signin/android')

setup google login for android in setting.gradle next, in MainApplication.java, we should own the google package add deoxyadenosine monophosphate in stick to code snip :

import co.apptailor.googlesignin.RNGoogleSigninPackage;  // <--- import

public class MainApplication extends Application implements ReactApplication {

  ......

  @Override
    protected List getPackages() {
      return Arrays.asList(
          new MainReactPackage(),
          new RNGoogleSigninPackage() // <-- this needs to be in the list
      );
    }
  ......

}

setup google login for android in MainApplication.java

Setting up Firebase

For iOS

now, we necessitate to get start on the firebase configuration. in firebase, we want to specify up ampere google defile app. merely when we place astir the authentication method on firebase this besides create associate in nursing google cloud app. inaugural, we need to create firebase io app in order to obtain GoogleServiceinfo.plist ampere express inch the screenshot below :add new firebase app nameadd new firebase app name following, we replicate the GoogleService-info.plist file to the Xcode stick out a read indiana the screenshot under :add google service plist to xcodeadd google service plist to xcode nowadays, we necessitate to attention deficit disorder the change by reversal node id present indium the GoogleService-info.plist file to the url type, a show in the screenshot under :get reverse client id from xcodeget reverse client id from xcode adjacent step be to fit to InfoURL Types then occupy the URL Schemes ampere show in the screenshot below :add url scheme to xcodeadd url scheme to xcode

For Android

first, we motivation to create associate in nursing android app on firebase. For that, we indigence deoxyadenosine monophosphate box name and certificate SHA-1 from our app. then, we can register the firebase app adenine show below :create new android firebase appcreate new android firebase app We displace induce the package name inch MainApplication.java of our stick out angstrom highlight in the code snip under :find out bundle name in android appfind out bundle name in android app future, we can get the SHA-1 key in the Keystore file. in the android/app directory, we can run the command :

cd android/app ; 
keytool -exportcert -keystore debug.keystore -list -v

generate sha-1 then, the SHA-1 key bequeath appear, arsenic testify indium the screenshot below :

generate sha1 for register android app in firebasegenerate sha1 for register android app in firebase after successfully create the firebase apparatus app, we need to download the google-services.json file and copy information technology to the directory, a show in the screenshot below :add google service json to android app folderadd google service json to android app folder now, the final step cost to set up a google sign-in part in android .

Installing the React Native Firebase Package

indium ordering to install react-native-firebase package version six, we need to range the surveil control indiana our project command motivate :

# Using npm 
npm install --save @react-native-firebase/app 
# Using Yarn 
yarn add @react-native-firebase/app

install react native firebase core component The @react-native-firebase/app module must constitute install earlier use any early firebase serve .

For iOS

We already have GoogleService-Info.plist add to Xcode. What constitute forget equal to allow firebase on io to practice the certificate. The firebase io SDK must cost configure during the bootstrap phase of your application. To do this, we need to unfold our /ios/{projectName}/AppDelegate.m file, and add the keep up : at the top of the file, we need to import the firebase SDK :

#import 

include Firebase inside your existing didFinishLaunchingWithOptions method, we want to lend the following to the top of the method acting :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add me --- \/
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }
  // Add me --- /\
  // ...
}

Firebase React Native ultimately, we want to run the pursue command to finalize the facility of the CocoaPods package :

cd ios ; pod install

CocoaPods install That 's information technology. nowadays we accept completed the initiation of the main firebase package on io

For Android

We indigence to configure firebase with android certificate. To allow firebase on android to use the certificate, the google-services plugin mustiness embody enable on the project. This command change to two file in the android directory. foremost, lend the google-services plugin arsenic deoxyadenosine monophosphate addiction inside your android/build.gradle file :

buildscript {
  dependencies {
    // ... other dependencies
    classpath 'com.google.gms:google-services:4.2.0'
    // Add me --- /\
  }
}
Lastly, execute the plugin by adding the following to the very bottom of your /android/app/build.gradle file:

apply plugin: 'com.google.gms.google-services'

add google service

React Native Firebase Authentication Module

after the facility complete, we need to set astir the parent firebase package. adjacent, we need to install the child faculty for authentication. For that, we need to open vitamin a concluding and run the follow command :

yarn add @react-native-firebase/auth

install react native firebase auth 

For iOS

We good need to install the pod again inch the dominate prompt :

cd ios/ && pod install

install cacao pod

For Android

You displace trace the instruction on the official document which embody entirely compulsory if you be exploitation react native < = 0.59 oregon need to manually integrate the library .

Activating Google Sign-in on Firebase

We need to go to the firebase console table. then, in the authentication section, we need to chink on google equally express indium the screenshot below :authentication method in firebaseauthentication method in firebase following, we want to enable the setup with the follow shape and save the configuration vitamin a usher in the screenshot below :activate project support emailactivate project support email in App.js, we motivation to consequence auth from the firebase software vitamin a picture in the code snip below :

import auth from '@react-native-firebase/auth';

import firebase auth package following, we need to integrate authentication config to the sign-in affair. after deoxyadenosine monophosphate successful login, we storehouse the accessToken and idToken to Firebase. now, we can try to login with google on our show react native app .

_signIn = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const {accessToken, idToken} = await GoogleSignin.signIn();
      setloggedIn(true);
      const credential = auth.GoogleAuthProvider.credential(
        idToken,
        accessToken,
      );
      await auth().signInWithCredential(credential);
    } catch (error) {

Firebase Login function immediately we have successfully complete the consolidation of google Sign-in in our react native app :result of google login with react nativeresult of google login with react native We buttocks see new datum that be add to the firebase console :firebase authentication consolefirebase authentication console

Tracking User Status

in orderliness to check the user ’ sulfur login status, we use firebase Auth. For that, we need to add the onAuthStateChanged method to useEffect indiana ordering for information technology to run inch every componentDidMount event call. besides, we need to pass vitamin a recall to the function name onAuthStateChanged ampere associate in nursing argument a picture indium the code snip below :

useEffect(() => {
    .............
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
  }, []);

subscribe to auth state indium the affair onAuthStateChanged, we handle local express data angstrom read inch the code snip downstairs :

function onAuthStateChanged(user) {
    setUser(user);
    console.log(user);
    if (user) setloggedIn(true);
  }

set user data nowadays, we indigence to store the drug user datum for the state. then, try to expose the drug user ’ second datum after a successful login. For that, we need to use the surveil piece of code :

{!user && You are currently logged out}
{user && (
  
    Welcome {user.displayName}
    
  
)}

code for display user info We will grow the following solution indiana our simulator :result on show auth usernamelogout firebase auth

Firebase Sign Out

For sign out, we need to remove all the user ’ randomness certificate and revoke the google sign-in keepsake. first gear, we want to expect for the GoogleSignin faculty to revoke the access and bless out. then, we visit the signOut method of Firebase auth in order to successfully logout. The overall code implementation be supply in the code snip below :

signOut = async () => {
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      auth()
        .signOut()
        .then(() => alert('Your are signed out!'));
      setloggedIn(false);
      // setuserInfo([]);
    } catch (error) {
      console.error(error);
    }
  };

Firebase sign-out function american samoa vitamin a leave, we can now perform logout mathematical process equally show indiana the code snip below :firebase react native sign out resultfirebase react native logout

Conclusion

in this tutorial, we learn how to set up google Login, along with store associate in nursing entree nominal, by leverage firebase into our react native project. beginning, we create the react native visualize with all the necessity component and function shape. then, we learn how to configure the google sign inch and firebase for both android and io platform. finally, we set up the firebase indiana react native app use a firebase box and display the user datum along with bless forbidden button. You can download the complete generator code of this tutorial from Github.

The dear partially exist that firebase & google Auth be support across wholly the mobile development lyric, such vitamin a flutter, swift operating room Kotlin. The configuration dance step and the architectural approach exist precisely the lapp .

Next Steps

now that you have determine approximately set up firebase google Login inch react native apps, here be some early subject you can count into :

If you wish this react native tutorial, please pass maine adenine star on the Github repo and plowshare this with your residential district. You can check out tied more release react native project along Instamobile. cheer !

source : https://dichvusuachua24h.com
category : Google

Dịch vụ liên quan

Compare Zoom and Google Hangouts Meet | IT@UMN | The people behind the technology

compare the feature of zoom ( umn.zoom.us ) and google haunt meet ( meet.google.com )...

Shareware – Wikipedia

proprietorship software whose full use be limited indium clock Shareware be adenine type of proprietary...

Android 13 – Wikipedia

thirteenth major version of the android mobile operate on system family Android 13 exist the...

Google Files has something ‘important’ in the pipeline

google get associate in nursing stallion suite of first-party apps that form vitamin a complete...

How to Use Google Earth in a Browser

google earth exist deoxyadenosine monophosphate fantastic creature that let you research the world from the...
Alternate Text Gọi ngay