Get Started with React Native + Google Sign In
Tags: reactnative, android, javascript, googlesignin
Published: 2020-04-19 20:15:35

In this post, I will be showing you guys how you can add sign in with Google feature in your app in a few simple steps.

I will be using a React Native Community supported package called `react-native-community/google-signin`.

##### Note :  `This post is made for react-native >= 0.60, if you are using react-native <= 0.59.x then this is not for you`

![google-signin](https://github.com/react-native-community/google-signin/raw/master/img/header.png)
##Features
- Support all 3 types of authentication methods (standard, with server-side validation or with offline access (aka server-side access))
- Promise-based API consistent between Android and iOS
- Typings for TypeScript and Flow
- Native signin buttons

### Versions 
####   React Native 0.61.5
####   react-native-community/google-signin 4.0.0

#Steps

- First, create the App using this command in terminal

```bash
npx react-native init TypeYourAppNameHere
```

- Navigate to RNGoogleSignInDemo in the terminal like this

```bash
cd TypeYourAppNameHere
```

- Now install `react-native-community/google-signin` dependency in your app

```bash
yarn add @react-native-community/google-signin

OR

npm install --save @react-native-community/google-signin
```

Since React Native >= 0.60 `AutoLinking` is supported therefore we don't need to run linking command.

But we do need to do some configuration in the native side but I promise it will be easy.

There are two ways to do this, with or without Firebase and I will be using the one with the Firebase. But for the other one, I can make a separate post for it. Do let me know should I?


# Firebase
- Search for Firebase and go to Firebase Console
- Create a project [ I have already created ] by clicking on `Add Project`. 

![firebase console](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase1.0.png?raw=true)

- Type your project Name after that click Continue

![firebase console](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase1.1.png?raw=true)

- Choose whether you want to add Analytics or not it's up to your preferences. By default, it's enabled. Press Continue.

![firebase console](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase1.2.png?raw=true)

Now your project is created.

![firebase console](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase1.3.png?raw=true)

 - Click the android icon in the firebase Console Dashboard

![firebase console](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase1.4.png?raw=true)

- Fill in the following fields of "Add Firebase to your Android app" to generate config file ( i.e. google-services.json)
 - Android package name
 - Debug signing certificate SHA-1
![firebase console](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase2.0.1.png?raw=true)

- For App's Package name you can find in `android/app/main/AndroidManifest.xml` file 


![AndroidManifest.xml](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase.2.1.png?raw=true)

- For  Debug signing certificate SHA-1

In terminal type command for Debug SHA1 (root of the project) 

##Mac/Linux

```bash
keytool -J-Duser.language=en -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
```

##Windows

– Change the directory to the JDK bin directory. The path of the JDK depends upon the operating system you are using

```bash
cd C:\Program Files\Java\jdk1.8.0_121\bin
```
– Now we have to run the following command using the keytool.exe file in JDK/bin

```bash
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
```

![terminal](https://aboutreact.com/wp-content/uploads/2018/09/key_store_ssh1.png)


If you don't like terminal then you use can Android Studio instead

![Android Studio 1](https://aboutreact.com/wp-content/uploads/2018/09/key_store_ssh4.png)
![Android Studio 2](https://aboutreact.com/wp-content/uploads/2018/09/key_store_ssh6.png)

- When you are done registering your android app with firebase then `Download the Config file` and place it in `android/app`

![firebase2.2.png](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase2.2.png?raw=true)
![firebase2.2.1.png](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase.2.2.1.png?raw=true)

- Add Firebase SDK in Project-level build.gradle  i.e. `android/build.gradle`
![firebase2.3.png](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase2.3.png?raw=true)
```gradle
buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        googlePlayServicesAuthVersion = "18.0.0" // Add this line
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.2")
        classpath 'com.google.gms:google-services:4.3.3' // Add this line
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
```

- Add Google Play Services plugin in App-level build.gradle (android/appp/build.gradle):

```gradle
apply plugin: 'com.google.gms.google-services' // Add at end of the file
```

### e.g. 
![firebase2.4.png](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase2.4.png?raw=true)

- In firebase, you will need to enable Google option in SignIn Method section

![firebase2.5.png](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase2.5.png?raw=true)

- While enabling Google, do copy the `Web Client ID` from there, we need this later on. 
 ![firebase2.6.png](https://github.com/anwargul0x/HookOn/blob/Host_Images/HostAssets/firebase2.6.png?raw=true)


# Let's get our hands dirty with the code

I will be making a simple app of just two components to App.js (already exists by default) and second will be Home.js.

- Import Public Api of `@react-native-community/google-signin`

```javascript
import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes,
} from '@react-native-community/google-signin';
```

- But before you can use above imports you need  call once, configure of GoogleSignin. You can call it in **ComponentDidMount** life Cycle method
or you can use **useEffect** Hook

```javascript
GoogleSignin.configure({
 webClientId: WebClientID, // 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
 forceCodeForRefreshToken: true, // [Android] related to `serverAuthCode`, read the docs link below *.
 accountName: '', // [Android] specifies an account name on the device that should be used
    });
```


- Sign in function 

```javascript

 signIn = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const info = await GoogleSignin.signIn();
      console.warn({userInfo: info});
      setUserInfo(info);
    } catch (error) {
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // user cancelled the login flow
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // operation (e.g. sign in) is in progress already
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // play services not available or outdated
      } else {
        // some other error happened
      }
    }
  };
```

- Sign out function

```javascript
  signOut = async () => {
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      setUserInfo(null); // Remember to remove the user from your app's state as well
    } catch (error) {
      console.error(error);
    }
  };
```

## Demo App Preview
![ezgif.com-optimize00986b78df17d105.gif](https://s4.gifyu.com/images/ezgif.com-optimize00986b78df17d105.gif)

*Do check the official Docs and if you have any questions let me know.*
{% github react-native-community/google-signin %}

I hope you like this post and I will be posting more post soon and most importantly All suggestions are welcome. 

![See Ya](https://miro.medium.com/max/960/0*0mc4QYmX3rCaQCh9)