React Native Google Sign In
Hello guys, Here is an example of Google Sign In in React Native Android and iOS App. In this example, we will see how to integrate Login via Google feature into your React Native Android and iOS application.
Google Sign In example can be very helpful to you as “Sign In with Google” is a must-have feature for every application which has logged in feature as it becomes much easier for the users to login without the mess of filing the registration form and confirming via mail or OTP.
If you are interested in adding more social login features then you can also see React Native Facebook Integration Example using Facebook SDK to integrate Facebook Login into your application.
For the current example of Google Sign In in React Native we are going to use react-native-google-signin
library, so let’s get started.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
To use GoogleSignin
, GoogleSigninButton
and statusCodes
we need to install react-native-google-signin
dependency and to install the dependency open the terminal and jump into your project using
cd ProjectName
Now run the following command to install the dependency
npm install react-native-google-signin --save
This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the dependency in your package.json file.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
Integration of Firebase SDK
Firebase is the easiest way to integrate Google SignIn in your Application. For the integration of firebase, I have specially made a different post in detail where you will see the point to point process to add Firebase in your Android and iOS app.
Please visit How to Integrate Firebase in Android and iOS App and come back for the next step.
Addition of URL Scheme for the iOS
I hope you have successfully integrated the Firebase in your Android and iOS Application. If you are doing the integration of Google Sign In only for the Android then you can skip the addition of URL else please follow the below instructions
1. You have to add an additional URL scheme for the Google Sign-In integration in iOS. This is not mentioned in the Firebase console because this process is a part of the react-native-google-signin
library.
2. For the addition of the URL Scheme, please open downloaded GoogleService-info.plist file in any code editor and copy REVERSED_CLIENT_ID string value for the next step (Just copy com.googleusercontent…………………..125)
3. Now open your project in Xcode
- Click on the project
- Select info
- Search for the URL Types and expand it
- Paste the copied string into the URL Schemes
- Add an URL type property in “Additional URL type properties” where “key” will be “item 0”, “Type” will be “String” and “Value” will be copied REVERSED_CLIENT_ID string.
Enable Authentication from Firebase Console
We have done all the steps of firebase integration and added the URL Scheme for iOS as well.
1. Now open your firebase project in Firebase console and click the Authentication option in the left side tab
2. Here click on the “Set up the sign-in method” and you will find all type of sign-in providers that firebase supports. Choose Google from the number of Sign-in providers and Enable it
3. Please scroll down and find web SDK configuration option, click on it and you will find web client ID, please remember you have to copy-paste this web client ID in the code below so keep it open or paste it somewhere.
Code for Google Sign In in React Native
Finally after lots of configuration please open App.js in any code editor and replace the code with the following code
App.js
Please do remember to replace REPLACE_YOUR_WEB_CLIENT_ID_HERE with your Web Client Id
// Example of Google Sign In in React Native Android and iOS App
// https://aboutreact.com/example-of-google-sign-in-in-react-native/
// Import React in our code
import React, {useState, useEffect} from 'react';
// Import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
Text,
View,
Image,
ActivityIndicator,
TouchableOpacity,
} from 'react-native';
// Import Google Signin
import {
GoogleSignin,
GoogleSigninButton,
statusCodes,
} from 'react-native-google-signin';
const App = () => {
const [userInfo, setUserInfo] = useState(null);
const [gettingLoginStatus, setGettingLoginStatus] = useState(true);
useEffect(() => {
// Initial configuration
GoogleSignin.configure({
// Mandatory method to call before calling signIn()
scopes: ['https://www.googleapis.com/auth/drive.readonly'],
// Repleace with your webClientId
// Generated from Firebase console
webClientId: 'REPLACE_YOUR_WEB_CLIENT_ID_HERE',
});
// Check if user is already signed in
_isSignedIn();
}, []);
const _isSignedIn = async () => {
const isSignedIn = await GoogleSignin.isSignedIn();
if (isSignedIn) {
alert('User is already signed in');
// Set User Info if user is already signed in
_getCurrentUserInfo();
} else {
console.log('Please Login');
}
setGettingLoginStatus(false);
};
const _getCurrentUserInfo = async () => {
try {
let info = await GoogleSignin.signInSilently();
console.log('User Info --> ', info);
setUserInfo(info);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_REQUIRED) {
alert('User has not signed in yet');
console.log('User has not signed in yet');
} else {
alert("Unable to get user's info");
console.log("Unable to get user's info");
}
}
};
const _signIn = async () => {
// It will prompt google Signin Widget
try {
await GoogleSignin.hasPlayServices({
// Check if device has Google Play Services installed
// Always resolves to true on iOS
showPlayServicesUpdateDialog: true,
});
const userInfo = await GoogleSignin.signIn();
console.log('User Info --> ', userInfo);
setUserInfo(userInfo);
} catch (error) {
console.log('Message', JSON.stringify(error));
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
alert('User Cancelled the Login Flow');
} else if (error.code === statusCodes.IN_PROGRESS) {
alert('Signing In');
} else if (
error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE
) {
alert('Play Services Not Available or Outdated');
} else {
alert(error.message);
}
}
};
const _signOut = async () => {
setGettingLoginStatus(true);
// Remove user session from the device.
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
// Removing user Info
setUserInfo(null);
} catch (error) {
console.error(error);
}
setGettingLoginStatus(false);
};
if (gettingLoginStatus) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
} else {
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Text style={styles.titleText}>
Example of Google Sign In in React Native
</Text>
<View style={styles.container}>
{userInfo !== null ? (
<>
<Image
source={{uri: userInfo.user.photo}}
style={styles.imageStyle}
/>
<Text style={styles.text}>
Name: {userInfo.user.name}
</Text>
<Text style={styles.text}>
Email: {userInfo.user.email}
</Text>
<TouchableOpacity
style={styles.buttonStyle}
onPress={_signOut}>
<Text>Logout</Text>
</TouchableOpacity>
</>
) : (
<GoogleSigninButton
style={{width: 312, height: 48}}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Light}
onPress={_signIn}
/>
)}
</View>
<Text style={styles.footerHeading}>
Google SignIn in React Native
</Text>
<Text style={styles.footerText}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
}
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
imageStyle: {
width: 200,
height: 300,
resizeMode: 'contain',
},
buttonStyle: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
width: 300,
marginTop: 30,
},
footerHeading: {
fontSize: 18,
textAlign: 'center',
color: 'grey',
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
This is how you can Integrate Google Sign In in React Native Android and iOS App. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Best tutorial on Planet for GOOGLE SIGN IN in react-native 🙂 I was searching this from last 4 days but now I have done this.
Thank you for your words 🙂 It will motivate me.
Hi there, yup this post is in fact nice and I
have learned lot of things from it on the topic of blogging.
thanks.
Thanks for the appreciation.
How can i refresh the token which i am getting through the package?
In Advance
Thanks
This can be used for that
i have one question, how to turn off that alert that “abcProject” wants to use google.com to sign in ? or how to change that alert? can you please help?
Hey that is for the confirmation from the use side, I can say not to violate data privacy law.
perfect bro! i love this tutorial.
superb tutorial it was. i am getting one error, says developer error status code=10 , getting error only in android. working fine in IOS. can you please suggest me, what can i do ?
Please have a look at this
Login is not saved in firebase console
That is completely a different thing. This example is for the social login you are talking about the Firebase Auth. Please have a look at Email Authentication using Firebase Authentication in React Native App
awesome way teach.
carry on ..
Hi after signing-in its displaying developer error. Please give me a solution…Thanks in Advance.
Developer Error means your app is not properly signed. Please have a look at this
Hello Firstly Awsome tutorial.I want to implement Google SignUp function but not able to find how to do that.May you help me?
Best sample ever!
nice code + beautiful design.
BTW, many thanks.