React Native Store/Retrieve Files on Google Drive
In this post, we will see how to Store/Retrieve Files on Google Drive using React Native App. In this example we will see how to integrate Google Drive to perform following operations in React Native App which will work for Android and iOS both.
- Create a directory on Google Drive
- Pick and Upload any File on Google Drive
- List Files from Google Drive (All Files + Filtered Files)
- Delete any File from Google Drive
- Download any File from Google Drive
We all know Google Drive is a file storage and synchronisation service developed by Google. Google Drive allows users to store files on their servers, synchronise files across devices, and share files.
If we talk about why people integrate Google Drive with any mobile app? The answer is to store the backup files of the mobile app and to store the data which belongs to the user and only and app does not required it for the analytics or for any other use.
How to Integrate Google Drive with React Native App
Let’s see how to integrate Google Drive.
Google provides a very nice API suite for the integration of Google Drive with any platform. We can simply use these HTTP APIs using fetch to manage Google Drive files but while preparing this example we found react-native-google-drive-api-wrapper, it is very simple to use library which provides all the necessary features as functions (internally it uses the same Google Drive V3 APIs). We are going to use the same for this example.
To access any Google Drive API we will need a token with proper permissions to access the files. We can get this token by providing Google Sign in feature (with permission to access Google Drive) in the app. This library does not provides any authorization mechanism so we will use an external Google Sign In library for the login and once user logged in we can request Google to give us a token to access the drive.
What can you do with Google Drive API?
- Download files from Google Drive and Upload files to Google Drive
- Search for files and folders stored in Google Drive. Create complex search queries that return any of the file metadata fields in the Files resource
- Let users share files, folders and drives to collaborate on content
- Combine with the Google Picker API to search all files in Google Drive, then return the file name, URL, last modified date, and user
- Create a dedicated Drive folder to store your application’s data so that the app cannot access all the user’s content stored in Google Drive. See Store application-specific data
Google Drive Example Explained
In this example we are going to create a Google Sign In on the first screen, once user logged in he/she will see home screen with all the options to navigate to different screens to upload, list, delete and download the file. We have create separate screen for each operation so that you can understand what exactly you need to perform that operation.
Now let’s start with the example.
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
This example needs different dependencies which is mentioned below. Please follow all the steps to run the app successfully. To install the dependency open the terminal and jump into your project
cd ProjectName
1. For this example we need Google Sign In in our App for which you can see Example of Google Sign In in React Native Android and iOS App, once you are done with the Google Sign In you can come back and can continue from next step.
If you are done with the Google Sign In integration, have you noticed scopes?
We need to send authorization token to the Drive API call. While generating this token we define scope to access the user data. When we configure Sign In in our app we define these scopes and which Google will confirms from the user after login. You can add the scopes according to your need, here you can find the list of scopes to add on the basis of different requirements. We have added so many scopes for this example as we are going to use maximum features of Google Drive API.
2. Once you are done with the Google Sign In, You can install following dependency to perform different operations on Google Drive
npm install react-native-google-drive-api-wrapper --save
3. Above dependency needs following dependency for the file download so we also need to install that also
npm install react-native-fs --save
4. Next, we are going to use the document picker to pick the file which we will upload to Google Drive, To use document picker install following dependency
npm install react-native-document-picker --save
5. That is enough to store and retrieve the files from Google Drive but in this example we will also use React navigation as we are going to switch the screens. So install the following react-navigation dependencies also
npm install @react-navigation/native --save
Other supporting libraries for react-navigation
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save
npm install @react-navigation/stack --save
CocoaPods Installation
Now we need to install pods
cd ios && pod install && cd ..
Enable Google Drive API from Google API Console
To use Google Drive API in our App we need to enable it. To enable the Google Drive API Please follow the below steps:
- Open Google API Console
- Find the project in top header (Firebase project you have create for Google Sign In)
- On dashboard you will see “ENABLE APIS AND SERVICES”, click on it
- In search bar search for “google drive”, you will see some results, just click on Google Drive API
- Please enable it, once you do it we have provided the permission successfully
Android Permission
In this example, we are going to store the downloaded file in the external storage and to do that we have to add permission into the AndroidManifest.xml
file. Please add the following permissions in your AndroidMnifest.xml. Go to YourProject -> android -> app -> main -> AndroidMnifest.xml
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
Permission | Purpose |
---|---|
WRITE_EXTERNAL_STORAGE | To create any file in external storage |
For more about the permission, you can see this post.
IOS Permission
For the RNFS to get the path to download the file we need to add following permission in iOS
1. Open the project YourProject -> ios -> YourProject.xcworkspace in XCode. Click on Project from the left sidebar
2. Select info tab which is info.plist
3. Click on the plus button to add following permission key and value which will be visible when permission dialog pops up.
Key | Value |
---|---|
Privacy – File Provider Presence Usage Description | App needs File Provider |
Project Directory/File Structure
If everything went well then you are ready to move to the next step.
To start with this example you need to create the following directory/file structure. This will have a src directory with all our code, src directory will have two more directory auth and googleDrivescreens. All these directory will have following files for complete example.
You can see
- App.js contains main navigation
- src/HomeScreen.js for the home screen listing
- src/auth/GoogleLoginScreen.js for the Google Sign In
- src/googleDrivescreens/GDUploadFileScreen.js to upload files to Google Drive
- src/googleDrivescreens/GDFilesListingScreen.js for the listing of Google Drive files
- src/googleDrivescreens/GDSingleFileScreen.js to get the content of text files without downloading it into the mobile device
- src/googleDrivescreens/GDDeleteFileScreen.js to delete any Google Drive file
- src/googleDrivescreens/GDDownloadFileScreen.js to download any Google Drive file into mobile device
Code to Store/Retrieve Files on Google Drive
You can find the complete code below. We request to please visit official library page to understand all the functions which we have used to create this example.
Now open App.js in any code editor and replace the code with the following code.
App.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
import 'react-native-gesture-handler';
// Import React
import React from 'react';
// Import Navigators from React Navigation
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
// Import all the screens needed
import GoogleLoginScreen from './src/auth/GoogleLoginScreen';
import HomeScreen from './src/HomeScreen';
import GDUploadFileScreen from './src/googleDrivescreens/GDUploadFileScreen';
import GDFilesListingScreen from './src/googleDrivescreens/GDFilesListingScreen';
import GDSingleFileScreen from './src/googleDrivescreens/GDSingleFileScreen';
import GDDeleteFileScreen from './src/googleDrivescreens/GDDeleteFileScreen';
import GDDownloadFileScreen from './src/googleDrivescreens/GDDownloadFileScreen';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName="GoogleLoginScreen"
screenOptions={{
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}>
<Stack.Screen
name="GoogleLoginScreen"
component={GoogleLoginScreen}
// Hiding header
options={{headerShown: false}}
/>
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{title: 'Google Drive Example'}}
/>
<Stack.Screen
name="GDUploadFileScreen"
component={GDUploadFileScreen}
options={{title: 'Upload File'}}
/>
<Stack.Screen
name="GDFilesListingScreen"
component={GDFilesListingScreen}
options={{title: 'Files'}}
/>
<Stack.Screen
name="GDSingleFileScreen"
component={GDSingleFileScreen}
options={{title: 'File Content'}}
/>
<Stack.Screen
name="GDDeleteFileScreen"
component={GDDeleteFileScreen}
options={{title: 'Delete File'}}
/>
<Stack.Screen
name="GDDownloadFileScreen"
component={GDDownloadFileScreen}
options={{title: 'Download File'}}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
src/HomeScreen.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// 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,
TouchableOpacity,
ScrollView,
} from 'react-native';
// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
const HomeScreen = ({navigation, route}) => {
//route.params.userInfo
// State Defination
const [userInfo, setUserInfo] = useState(null);
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity onPress={_signOut}>
<Text style={{marginRight: 10, color: 'white'}}>
Logout
</Text>
</TouchableOpacity>
),
});
}, [navigation]);
useEffect(() => {
setUserInfo(route.params.userInfo);
}, []);
// To sign out from Google Login
const _signOut = async () => {
// Remove user session from the device.
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
// Removing user Info
setUserInfo(null);
navigation.replace('GoogleLoginScreen');
} catch (error) {
console.error(error);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<>
<View style={{flexDirection: 'row'}}>
{userInfo ? (
<Image
source={{uri: userInfo.user.photo}}
style={styles.imageStyle}
/>
) : null}
<View style={{flexDirection: 'column'}}>
<Text style={styles.text}>
User Name: {userInfo ? userInfo.user.name : ''}
</Text>
<Text style={styles.text}>
Use Email: {userInfo ? userInfo.user.email : ''}
</Text>
</View>
</View>
<ScrollView>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() =>
navigation.navigate('GDUploadFileScreen')
}>
<Text>Select and Upload File on Google Drive</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() =>
navigation.navigate(
'GDFilesListingScreen',
{type: 'all'}
)
}>
<Text>Listing of Files from Google Drive</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() =>
navigation.navigate(
'GDFilesListingScreen',
{type: 'filtered'}
)
}>
<Text style={{textAlign: 'center'}}>
Get Specific File Content from Google Drive
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() =>
navigation.navigate('GDSingleFileScreen')
}>
<Text style={{textAlign: 'center'}}>
Get Single File Content from Google Drive
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() =>
navigation.navigate('GDDeleteFileScreen')
}>
<Text>Delete any File from Google Drive</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() =>
navigation.navigate('GDDownloadFileScreen')
}>
<Text>Download File from Google Drive</Text>
</TouchableOpacity>
</ScrollView>
</>
<Text style={styles.footerHeading}>
Store/Retrieve Files on Google Drive
</Text>
<Text style={styles.footerText}>www.aboutreact.com</Text>
</View>
</SafeAreaView>
);
};
export default HomeScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
},
imageStyle: {
width: 40,
height: 40,
borderRadius: 40 / 2,
marginRight: 16,
},
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',
},
});
src/auth/GoogleLoginScreen.js
Please replace REPLACE_YOUR_WEBCLIENT_ID with your webClientId
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// 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,
ActivityIndicator,
} from 'react-native';
// For Google Signin
import {
GoogleSignin,
GoogleSigninButton,
statusCodes,
} from 'react-native-google-signin';
const GoogleLoginScreen = ({navigation}) => {
const [loading, setLoading] = useState(true);
useEffect(() => {
// Initial configuration
GoogleSignin.configure({
// Mandatory method to call before calling signIn()
scopes: [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.metadata',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive.metadata.readonly',
'https://www.googleapis.com/auth/drive.apps.readonly',
'https://www.googleapis.com/auth/drive.photos.readonly',
],
// Repleace with your webClientId
// Generated from Firebase console
webClientId: 'REPLACE_YOUR_WEBCLIENT_ID',
});
// Check if user is already signed in
_isSignedIn();
}, []);
// To prompt google Signin Widget
const _signIn = async () => {
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);
navigation.replace('HomeScreen', {userInfo: userInfo});
} catch (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 {
console.log('error.message', JSON.stringify(error));
alert(error.message);
}
}
};
// Check if User is signned in or not?
const _isSignedIn = async () => {
const isSignedIn = await GoogleSignin.isSignedIn();
if (isSignedIn) {
console.log('User is already signed in');
// Get User Info if user is already signed in
try {
let info = await GoogleSignin.signInSilently();
console.log('User Info --> ', info);
navigation.replace('HomeScreen', {userInfo: 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", error);
}
}
}
setLoading(false);
};
if (loading) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
} else {
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<Text style={styles.titleText}>
Store / Retrieve Files from Google Drive{' '}
using React Native App
</Text>
<View style={styles.container}>
<GoogleSigninButton
style={{width: 312, height: 48}}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={_signIn}
/>
</View>
<Text style={styles.footerHeading}>
Store/Retrieve Files on Google Drive
</Text>
<Text style={styles.footerText}>www.aboutreact.com</Text>
</View>
</SafeAreaView>
);
}
};
export default GoogleLoginScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
padding: 10,
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
footerHeading: {
fontSize: 18,
textAlign: 'center',
color: 'grey',
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});
src/googleDrivescreens/GDUploadFileScreen.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// Import React in our code
import React, {useState} from 'react';
// Import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
Text,
View,
ActivityIndicator,
TouchableOpacity,
TextInput,
} from 'react-native';
// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
// To manage local files
import RNFS from 'react-native-fs';
// To pick the file from local file system
import DocumentPicker from 'react-native-document-picker';
const APP_DIRECTORY = 'AboutReactAppExample';
const GDUploadFileScreen = () => {
// State Defination
const [loading, setLoading] = useState(false);
const [filePath, setFilePath] = useState({});
const [inputTextValue, setInputTextValue] = useState('');
const _chooseFile = async () => {
// Opening Document Picker to select one file
try {
const fileDetails = await DocumentPicker.pick({
// Provide which type of file you want user to pick
type: [DocumentPicker.types.allFiles],
});
console.log('fileDetails : ' + JSON.stringify(fileDetails));
// Setting the state for selected File
setFilePath(fileDetails);
} catch (error) {
setFilePath({});
// If user canceled the document selection
alert(
DocumentPicker.isCancel(error)
? 'Canceled'
: 'Unknown Error: ' + JSON.stringify(error),
);
}
};
const _initGoogleDrive = async () => {
// Getting Access Token from Google
let token = await GoogleSignin.getTokens();
if (!token) return alert('Failed to get token');
console.log('res.accessToken =>', token.accessToken);
// Setting Access Token
GDrive.setAccessToken(token.accessToken);
// Initializing Google Drive and confirming permissions
GDrive.init();
// Check if Initialized
return GDrive.isInitialized();
};
const _uploadDriveDataImage = async () => {
try {
// Check if file selected
if (Object.keys(filePath).length == 0)
return alert('Please Select any File');
setLoading(true);
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Convert Selected File into base64
let fileContent = await RNFS.readFile(filePath.uri, 'base64');
// console.log('fileContent -> ', JSON.stringify(fileContent));
// Create Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
// Create Multipart and Upload
let result = await GDrive.files.createFileMultipart(
fileContent,
filePath.type,
{
parents: [directoryId],
name: filePath.name,
},
true,
);
// Check upload file response for success
if (!result.ok) return alert('Uploading Failed');
// Getting the uploaded File Id
let fileId = await GDrive.files.getId(
filePath.name,
[directoryId],
filePath.type,
false,
);
alert(`Uploaded Successfull. File Id: ${fileId}`);
setFilePath({});
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
const _uploadDriveData = async () => {
try {
// Check if file selected
if (!inputTextValue) return alert('Please Enter Some Input');
setLoading(true);
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Create Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
let fileName = new Date().getTime() + '.txt';
// Check upload file response for success
let result = await GDrive.files.createFileMultipart(
inputTextValue,
'application/text',
{
parents: [directoryId],
name: fileName,
},
false,
);
// Check upload file response for success
if (!result.ok) return alert('Uploading Failed');
// Getting the uploaded File Id
let fileId = await GDrive.files.getId(
fileName,
[directoryId],
'application/text',
false,
);
setInputTextValue('');
alert(`Uploaded Successfull. File Id: ${fileId}`);
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
return (
<>
{loading ? (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Text style={styles.titleText}>
Upload Input Text as File on Google Drive
</Text>
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Please Enter Text to Upload as a File"
onChangeText={(input) => setInputTextValue(input)}
value={inputTextValue}
/>
<TouchableOpacity
style={styles.buttonStyle}
onPress={_uploadDriveData}>
<Text>uploadDriveFile</Text>
</TouchableOpacity>
<View style={styles.deviderContainer}>
<View style={styles.devider} />
<Text>OR</Text>
<View style={styles.devider} />
</View>
<Text style={styles.titleText}>
Choose File and Upload to Google Drive
</Text>
<TouchableOpacity
activeOpacity={0.5}
style={styles.buttonStyle}
onPress={_chooseFile}>
<Text style={styles.textStyleWhite}>
Choose Image{' '}
(Current Selected: {filePath.uri ? 1 : 0})
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={_uploadDriveDataImage}>
<Text>uploadDriveDataImage</Text>
</TouchableOpacity>
</View>
<Text style={styles.footerHeading}>
Store/Retrieve Files on Google Drive
</Text>
<Text style={styles.footerText}>www.aboutreact.com</Text>
</View>
</SafeAreaView>
)}
</>
);
};
export default GDUploadFileScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
padding: 10,
},
titleText: {
fontSize: 16,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
imageStyle: {
width: 20,
height: 30,
resizeMode: 'contain',
},
buttonStyle: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
width: 300,
marginTop: 16,
},
footerHeading: {
fontSize: 18,
textAlign: 'center',
color: 'grey',
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
deviderContainer: {
flexDirection: 'row',
alignItems: 'center',
marginVertical: 16,
},
devider: {
width: 150,
height: 1,
marginHorizontal: 16,
backgroundColor: 'grey',
},
inputStyle: {
height: 40,
width: 300,
borderColor: 'grey',
borderWidth: 1,
padding: 10,
},
});
src/googleDrivescreens/GDFilesListingScreen.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// 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,
ActivityIndicator,
FlatList,
} from 'react-native';
// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
const APP_DIRECTORY = 'AboutReactAppExample';
const GDFilesListingScreen = ({route}) => {
// State Defination
const [listData, setListData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (route.params.type == 'all') _getAllFilesList();
else _getAllMyAppFilesList();
}, []);
const _initGoogleDrive = async () => {
// Getting Access Token from Google
let token = await GoogleSignin.getTokens();
if (!token) return alert('Failed to get token');
console.log('res.accessToken =>', token.accessToken);
// Setting Access Token
GDrive.setAccessToken(token.accessToken);
// Initializing Google Drive and confirming permissions
GDrive.init();
// Check if Initialized
return GDrive.isInitialized();
};
const _getAllFilesList = async () => {
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
let data = await GDrive.files.list({
q: GDrive._stringifyQueryParams(
{trashed: false}, '', ' and ', true
),
});
let result = await data.json();
setListData(result.files);
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
const _getAllMyAppFilesList = async () => {
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Create/Get Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
let data = await GDrive.files.list({
q:
GDrive._stringifyQueryParams(
{
trashed: false,
// mimeType: 'application/text'
},
'',
' and ',
true,
) + ` and '${directoryId}' in parents`,
});
let result = await data.json();
setListData(result.files);
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
const ItemView = ({item}) => {
return (
// FlatList Item
<View style={{padding: 10}}>
<Text style={styles.item} onPress={() => getItem(item)}>
File Id: {item.id}
{'\n'}
File Name: {item.name}
{'\n'}
Mine Type: {item.mimeType}
</Text>
</View>
);
};
const ItemSeparatorView = () => {
return (
// FlatList Item Separator
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
};
const getItem = (item) => {
//Function for click on an item
alert(JSON.stringify(item));
};
return (
<SafeAreaView style={styles.container}>
<Text style={styles.titleText}>
Listing of Files from Google Drive
</Text>
{route.params.type == 'all' ? null : (
<Text style={{textAlign: 'center'}}>
Directory: {APP_DIRECTORY}
</Text>
)}
{loading ? (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : (
<FlatList
data={listData}
//data defined in constructor
ItemSeparatorComponent={ItemSeparatorView}
//Item Separator View
renderItem={ItemView}
keyExtractor={(item, index) => index.toString()}
/>
)}
<Text style={styles.footerText}>www.aboutreact.com</Text>
</SafeAreaView>
);
};
export default GDFilesListingScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 10,
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});
src/googleDrivescreens/GDSingleFileScreen.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// 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,
ActivityIndicator,
FlatList,
} from 'react-native';
// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
const APP_DIRECTORY = 'AboutReactAppExample';
const GDSingleFileScreen = () => {
// State Defination
const [listData, setListData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
_getAllMyAppFilesList();
}, []);
const _initGoogleDrive = async () => {
// Getting Access Token from Google
let token = await GoogleSignin.getTokens();
if (!token) return alert('Failed to get token');
console.log('res.accessToken =>', token.accessToken);
// Setting Access Token
GDrive.setAccessToken(token.accessToken);
// Initializing Google Drive and confirming permissions
GDrive.init();
// Check if Initialized
return GDrive.isInitialized();
};
const _getAllMyAppFilesList = async () => {
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Create/Get Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
let data = await GDrive.files.list({
q:
GDrive._stringifyQueryParams(
{
trashed: false,
// mimeType: 'application/text'
},
'',
' and ',
true,
) + ` and '${directoryId}' in parents`,
});
let result = await data.json();
setListData(result.files);
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
const ItemView = ({item}) => {
return (
// FlatList Item
<View style={{padding: 10}}>
<Text style={styles.item} onPress={() => getItem(item)}>
File Id: {item.id}
{'\n'}
File Name: {item.name}
{'\n'}
Mine Type: {item.mimeType}
</Text>
</View>
);
};
const ItemSeparatorView = () => {
return (
// FlatList Item Separator
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
};
const getItem = async (item) => {
if (
!(
item.mimeType.match(/text/i) ||
item.mimeType == 'application/x-javascript' ||
item.mimeType == 'application/json'
)
)
return alert(
'Sorry we only deal with the text files, Not in binaries'
);
setLoading(true);
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
let result = await GDrive.files.get(item.id, {alt: 'media'});
if (result.ok) {
result = await result.text();
console.log('File Content: ' + result);
alert('File Content: ' + result);
}
} catch (error) {
alert(error);
console.log(error);
}
setLoading(false);
};
return (
<SafeAreaView style={styles.container}>
<Text style={styles.titleText}>
Get any Google Drive File (Text File) Content
</Text>
{loading ? (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : (
<FlatList
data={listData}
//data defined in constructor
ItemSeparatorComponent={ItemSeparatorView}
//Item Separator View
renderItem={ItemView}
keyExtractor={(item, index) => index.toString()}
/>
)}
<Text style={styles.footerText}>www.aboutreact.com</Text>
</SafeAreaView>
);
};
export default GDSingleFileScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 10,
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});
src/googleDrivescreens/GDDeleteFileScreen.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// 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,
ActivityIndicator,
FlatList,
Alert,
} from 'react-native';
// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
const APP_DIRECTORY = 'AboutReactAppExample';
const GDDeleteFileScreen = () => {
// State Defination
const [listData, setListData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
_getAllMyAppFilesList();
}, []);
const _initGoogleDrive = async () => {
// Getting Access Token from Google
let token = await GoogleSignin.getTokens();
if (!token) return alert('Failed to get token');
console.log('res.accessToken =>', token.accessToken);
// Setting Access Token
GDrive.setAccessToken(token.accessToken);
// Initializing Google Drive and confirming permissions
GDrive.init();
// Check if Initialized
return GDrive.isInitialized();
};
const _getAllMyAppFilesList = async () => {
setLoading(true);
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Create/Get Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
let data = await GDrive.files.list({
q: GDrive._stringifyQueryParams(
{trashed: false}, '', ' and ', true) +
` and '${directoryId}' in parents`,
});
let result = await data.json();
setListData(result.files);
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
const _deleteDriveData = async (item) => {
try {
setLoading(true);
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Create/Get Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
let result = await GDrive.files.delete(item.id);
if (!result.ok) {
alert('File Deletion Failed');
}
_getAllMyAppFilesList();
} catch (error) {
alert(error);
console.log(error);
}
setLoading(false);
};
const ItemView = ({item}) => {
return (
// FlatList Item
<View style={{padding: 10}}>
<Text style={styles.item} onPress={() => getItem(item)}>
File Id: {item.id}
{'\n'}
File Name: {item.name}
{'\n'}
Mine Type: {item.mimeType}
</Text>
<Text style={{color: 'red'}}>Click to Delete</Text>
</View>
);
};
const ItemSeparatorView = () => {
return (
// FlatList Item Separator
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
};
const getItem = (item) => {
Alert.alert(
'Warning',
'Are you sure you want to delete the file from Google Drive?',
[
{
text: 'Yes',
onPress: () => _deleteDriveData(item),
},
{
text: 'No',
onPress: () => console.log('No Pressed'),
},
],
{cancelable: true},
);
};
return (
<SafeAreaView style={styles.container}>
<Text style={styles.titleText}>
Delete any File from Google Drive
</Text>
{loading ? (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : (
<FlatList
data={listData}
//data defined in constructor
ItemSeparatorComponent={ItemSeparatorView}
//Item Separator View
renderItem={ItemView}
keyExtractor={(item, index) => index.toString()}
/>
)}
<Text style={styles.footerText}>www.aboutreact.com</Text>
</SafeAreaView>
);
};
export default GDDeleteFileScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 10,
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});
src/googleDrivescreens/GDDownloadFileScreen.js
// Store/Retrieve Files on Google Drive using React Native App
// https://aboutreact.com/react-native-google-drive/
// 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,
ActivityIndicator,
FlatList,
} from 'react-native';
// For Google Signin
import {GoogleSignin} from 'react-native-google-signin';
// For Google Drive
import GDrive from 'react-native-google-drive-api-wrapper';
// To manage local files
import RNFS from 'react-native-fs';
const APP_DIRECTORY = 'AboutReactAppExample';
const GDDownloadFileScreen = () => {
// State Defination
const [listData, setListData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
_getAllMyAppFilesList();
}, []);
const _initGoogleDrive = async () => {
// Getting Access Token from Google
let token = await GoogleSignin.getTokens();
if (!token) return alert('Failed to get token');
console.log('res.accessToken =>', token.accessToken);
// Setting Access Token
GDrive.setAccessToken(token.accessToken);
// Initializing Google Drive and confirming permissions
GDrive.init();
// Check if Initialized
return GDrive.isInitialized();
};
const _getAllMyAppFilesList = async () => {
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
// Create/Get Directory on Google Device
let directoryId = await GDrive.files.safeCreateFolder({
name: APP_DIRECTORY,
parents: ['root'],
});
console.log('directoryId -> ', directoryId);
let data = await GDrive.files.list({
q:
GDrive._stringifyQueryParams(
{
trashed: false,
// mimeType: 'application/text'
},
'',
' and ',
true,
) + ` and '${directoryId}' in parents`,
});
let result = await data.json();
setListData(result.files);
} catch (error) {
console.log('Error->', error);
alert(`Error-> ${error}`);
}
setLoading(false);
};
const ItemView = ({item}) => {
return (
// FlatList Item
<View style={{padding: 10}}>
<Text style={styles.item} onPress={() => getItem(item)}>
File Id: {item.id}
{'\n'}
File Name: {item.name}
{'\n'}
Mine Type: {item.mimeType}
</Text>
<Text style={{color: 'red'}}>Click to Download</Text>
</View>
);
};
const ItemSeparatorView = () => {
return (
// FlatList Item Separator
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
};
const getItem = async (item) => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'External Storage Write Permission',
message: 'App needs write permission',
},
);
// If WRITE_EXTERNAL_STORAGE Permission is granted
if (granted != PermissionsAndroid.RESULTS.GRANTED) return;
} catch (err) {
console.warn(err);
alert('Write permission err', err);
return;
}
}
try {
if (!(await _initGoogleDrive())) {
return alert('Failed to Initialize Google Drive');
}
console.log(
`Destination: ${RNFS.DocumentDirectoryPath}/${item.name}`
);
setLoading(true);
GDrive.files
.download(item.id, {
toFile: `${RNFS.DocumentDirectoryPath}/${item.name}`,
method: 'POST',
headers: {
Accept: 'application/json',
},
})
.promise.then((res) => {
console.log({res});
setLoading(false);
if (res.statusCode == 200 && res.bytesWritten > 0)
alert('File download successful');
});
} catch (error) {
alert(error);
console.log(error);
setLoading(false);
}
};
return (
<SafeAreaView style={styles.container}>
<Text style={styles.titleText}>
Download any Google Drive File
</Text>
{loading ? (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : (
<FlatList
data={listData}
//data defined in constructor
ItemSeparatorComponent={ItemSeparatorView}
//Item Separator View
renderItem={ItemView}
keyExtractor={(item, index) => index.toString()}
/>
)}
<Text style={styles.footerText}>www.aboutreact.com</Text>
</SafeAreaView>
);
};
export default GDDownloadFileScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding: 10,
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
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 Store/Retrieve files on Google Drive using React Native 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. 🙂