Recognized by Clutch.co as a top-rated Mobile App Development Company.
folio3-mobile
US 408 365 4638
START YOUR PROJECT
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise
    • AR/VR
    • IoT
    • Wearables
    • Field Sales
    • On Demand Apps
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical & Life Sciences
    • Manufacturing
    • Automotive
    • Logistics
    • Education
  • Technologies
    • Native Mobile Apps
      • iOS
      • Android
    • Cross Platform Apps
      • React Native
      • Flutter
      • Ionic
      • Xamarin
      • NativeScript
      • Sencha
  • Portfolio
  • Blog
  • Contact Us

Integration of Google drive API with React Native

Published by: Noc Folio3 | September 21, 2021 msaqlain
SCROLL AND BE AMAZED!
Home > App Development • Blog • React Native > Integration of Google drive API with React Native

React native has been one of the successful Mobile app framework that allows to create applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows and UWP developed on Javascript. With the pace of time, many new cross-platform mobile development tools have been introduced. Despite this all, React Native has still been one of the top choices.

In this era, where Google has covered almost every device. The need of authentication has been clearly reduced to just a Google sign-in. Mostly, the users prefer to use a single account for login, thanks to Google. While, other popular services provided by Google like Google Drive is quite handy too.

In this blog, you’ll learn how to integrate the Google Drive API with React Native and cover basic operations enough for storing your content, or creating Backups. The steps mentioned below will cover the following,

  1. Creating a folder on Google Drive
  2. Creating a file in that folder
  3. Listing the uploaded files
  4. Accessing the contents.

We will be using the Google Drive API Wrapper for React Native, which is react-native-google-drive-api-wrapper.

It is assumed that you have already integrated the Google Sign-In API with your app. If not, follow the steps mentioned in react-native-google-signin, integrate it and get the web client Id.

Step#1: Installing the Google Drive API Wrapper

Follow the simple guide and install the wrapper. Don’t forget to install the react-native-fs too. Once installed, make sure everything is linked and configured properly.

Step#2: Configure the Google Sign-in

You must have web client id obtained from Google Developers Console in your credentials tab for the project created. Then use the code given below.

import {GoogleSignin, statusCodes} from 'react-native-google-signin';
	import GDrive from 'react-native-google-drive-api-wrapper';

//In your useEffect / componentDidMount function	
  GoogleSignin.configure({
		scopes: // Will be covered in Step 4
webClientId:'xyz0yxa-xyzxyzxyznlpsi.apps.googleusercontent.com', 
offlineAccess: true,
});

Step#3: Setup User Sign-in, obtain the Access Token and Initialize the GDrive API

Setup the code for User sign-in through react-native-google-signin. Once signed in, you can obtain the access token and set the obtained token for GDrive API and initialize it.

signIn = async () => {
    	try {
      		await GoogleSignin.hasPlayServices();
      		const userInfo = await GoogleSignin.signIn();
     		const token = (await GoogleSignin.getTokens()).accessToken;
		//Save the Token and User Info
		//To get the user email, userInfo.user.email

// Set the token for Gdrive
GDrive.setAccessToken(this.state.accToken);  
GDrive.init(); // Initialize the GDrive

	//You can extract the error types from statusCodes as follows.

  	} catch (error) {
      	if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        			// user cancelled the login flow
      	} else if (error.code === statusCodes.IN_PROGRESS) {
       			// operation (f.e. 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
}
    	}};

Step#4: Understanding and Setting Scopes

In order to perform operations like (listing, creating folders, uploading files, etc.) we’ve to understand the specific scopes required. Scopes represent the access you need from the user. Sensitive scopes might require you to verify your App. You can check the recommended, sensitive and restricted scopes for Google Drive API here.

Our use case here is simply to create a file in a folder, get the list of files in a folder, and get contents of a file (An enough approach for Backing up the data on Google Drive).

So, for that we will be using the scopes given below,

GoogleSignin.configure({
		scopes: [
        		'https://www.googleapis.com/auth/drive.appdata',
        		'https://www.googleapis.com/auth/drive.file',
      		], // what API you want to access on behalf of the user, default is
   // email and profile
webClientId:'xyz0yxa-xyzxyzxyznlpsi.apps.googleusercontent.com', 
offlineAccess: true,
});

Step#5: Creating a Folder

Once the GDrive is initialised, we can create a folder of our concern, i.e. My Diaries/ My Backups, or whatever your use case is.
The method safeCreateFolder will create a folder if it doesn’t exist, or returns the folderId if it exists. The FolderId is required to access the contents of folder.

if (GDrive.isInitialized()) {
//Google Drive is Initialized Now!!
        		try {
          		  const folderId = await GDrive.files.safeCreateFolder({
            		  name: 'My Backups',
          		  parents: ['root'],
          		}); 
} catch(err) {
   //.. catch the error accordingly
} }

Step#6: Creating a file

To create a text file in the same folder, get the folderId of that folder and create the file in it. We’ll be using the createFileMultipart method to achieve this.

let content=”My first text file on GDrive”
	const folderId = await GDrive.files.safeCreateFolder({
        		name: 'My Backups',
       		 parents: ['root'],
      		});
	//Now to upload it
	//Put the folderId as parent for creating the file
	GDrive.files.createFileMultipart(
          		content,
          		'text/plain',
         		 {
            			parents: [folderId],
            			name: 'Backup1'.txt',
          		},
          		false,
        		)
    .then(response => {
 		//DONE
}).catch(er => {
    //
 catch the error accordingly
});

Step#7: Listing the files

To list the files in any folder, obtain the folderId of that folder and use the below code.

GDrive.files.list({
       q: "'" + folderId + "' in parents",
})
.then(res => res.json())
.then(data => {
	// access the files name like data.files[1].name
	// data.files is the array having the list of files
})
.catch(err => {
       //
 catch the error accordingly
});

Step#8: Access the contents of File

To access the data in the file, simply get the id of the file by data.files[0].id, and access the contents through that id.

GDrive.files.get(id, {alt: 'media'})
.then(res => { //access the data in res}
.catch(err=> { //
 catch the error accordingly }

All the methods used in the above steps are listed in react-native-google-drive-api-wrapper. If you want to use other methods, go through the documentation.

So, in this way you can integrate the Google Drive API with React native and store your files. There can be variety of use cases that can be achieved through Google Drive, whether that is backup of your local data which you want to store or setting up the whole mechanism of JSON based import/export of files. Thanks for reading,
Don’t forget to give a thumbs up!


About Noc Folio3

Newsletter

Search

Archives

  • December 2023
  • April 2023
  • March 2023
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • October 2021
  • September 2021
  • May 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019
  • May 2019

Recent Posts

  • Exploring Flutter Navigation: From Basics to Advanced Routes
  • Web UI Test Automation with Pytest-BDD
  • How to fix IOS compass calibration issues
  • Testing Android Applications With Perfect Coverage
  • How to use useRef hook efficiently? – React

Tags

  • android
  • angular-state-management
  • Automation
  • Compass
  • cross-platform
  • css
  • development
  • firebase
  • hooks
  • ios
  • learn-ngrx
  • ngrx-beginner
  • ngrx/store
  • QA
  • react-native
  • reactjs
  • scss
  • stylesheet
  • styling
  • Testing
  • Test Script
  • UI-UX

Newsletter

Newsletter

Post navigation

Previous Responsive UI with Flutter
Next Fetching Data from Google Fit into a React Native Application
Schedule an Appointment with our Mobile App Development Expert
Footer Menu
  • Company
    • About Us
    • Portfolio
    • Blog
    • Careers
    • Contact Us
  • Solutions
    • Apps Discovery Services
    • Team Augmentation
    • Enterprise App Development
    • AR/VR Application Development
    • IoT Application Development
    • Wearables Apps Development
    • Field Sales
    • On-Demand Apps Development
  • Technologies
    • iOS
    • Android
    • React Native
    • Flutter
    • Ionic
    • Xamarin
    • NativeScript
    • HTML5
    • Sencha
  • Industries
    • Retail
    • Agriculture
    • Healthcare
    • Pharmaceutical
    • Manufacturing
    • Automotive
    • Logistics
    • Education

US Office

Belmont, California – 1301 Shoreway Road, Suite 160, Belmont, CA 94002

Pleasanton, California – 6701 Koll Center Parkway, #250 Pleasanton, CA 94566

Tel: +1 408 365 4638
Support: +1 (408) 512 1812

Mexico Office

Amado Nervo #2200, Edificio Esfera 1 piso 4, Col. Jardines del Sol, CP. 45050, Zapopan, Jalisco, Mexico

Bulgaria Office

49 Bacho Kiro Street, Sofia, 1000, Bulgaria

Canada Office​

895 Don Mills Road, Two Morneau Shepell Centre, Suite 900, Toronto, Ontario, M3C 1W3, Canada

UK Office

Export House, Cawsey Way, Woking Surrey, GU21 6QX

Tel: +44 (0) 14 8361 6611

UAE Office

Dubai, UAE – Dubai Internet City, 1st Floor, Building Number 12, Premises ED 29, Dubai, UAE

Tel: +971-55-6540154
Tel: +971-04-2505173

Pakistan Office

Folio3 Tower, Plot 26, Block B, SMCH Society, Main Shahrah-e-Faisal, Karachi.

First Floor, Blue Mall 8-R, MM Alam Road Gulberg III, Lahore.

Tel: +92-21-3432 3721-4 

© 2025, Folio3 Software Inc., All rights reserved.

  • Privacy policy and terms of use
  • Cookie Policy
Follow us on
Facebook-f Linkedin-in Instagram

Get a free app audit

[contact-form-7 id="3548" title="Float Banner Form"]