Upload Photo With React Native and Firebase
Mega Package Sale is ON! Become ALL of our React Native codebases at 80% OFF discount 🔥
Using React Native yous can build a variety of app screens that are cross-platform using JavaScript as the main programming linguistic communication. One such app screen feature is uploading photos which is quite a common feature in social media apps. Uploading photos to Firebase Storage is a common practice in React Native apps that take backend integration with Firebase, such as our React Native templates. In this tutorial, let's build a demo app in which yous are going to create a simple screen that allows you lot to selection an image from the app running on the device, using an prototype picker and upload it to the Firebase Deject Storage. The second screen is going to brandish these images.
Getting started
Outset by creating a new react native project. Run the post-obit control from a terminal window. Later the project directory is created, navigate within it and install the required dependencies.
npx react-native init uploadStorageDemo cd uploadStorageDemo yarn add react-native-progress react-native-prototype-picker
Practise notation that this tutorial uses a react-native version above 0.60.x
. If y'all are using a version below that, brand sure to seek guidance on how to link native binaries for the libraries mentioned in this tutorial. To follow instructions on how to configure react-native-prototype-picker
for each mobile platform, I highly recommend you lot to get through the official docshither. For iOS, make sure to install pods.
cd ios/ && pod install # after pods install cd ..
Create an upload screen
The current demo app is going to contain 1 screen that volition help the user to select an image from the device's photo library. Create a file called UploadScreen.js
inside src/screens/
directory and the following mock snippet for at present.
import * every bit React from 'react'; import { Text, View } from 'react-native'; export default office UploadScreen() { return ( <View way={{ flex: i, justifyContent: 'heart', alignItems: 'center' }}> <Text>Upload!</Text> </View> ); }
Open up App.js
file and import the AppTabs
.
import React from 'react'; import { StatusBar } from 'react-native'; import UploadScreen from './src/screens/UploadScreen'; const App = () => { return ( <> <StatusBar barStyle="dark-content" /> <UploadScreen /> </> ); }; export default App;
At present, go back to the terminal window and build the react native app for the platform or the OS you wish to run information technology on.
# for iOS npx react-native run-ios # for Android npx react-native run-android
I am going to use the iOS simulator for this demo. Open the app to the simulator and y'all are going to see the following output.
Create a new Firebase Project
To access the Firebase credentials for each mobile OS platform and configure them to use the Firebase SDK, create a new Firebase projection from theFirebase console, or if you already have access to a projection in your console, you tin skip this step. Create a new projection as shown beneath. Add the details of your Firebase project. Click the push "Create project", and you should be redirected to the dashboard screen. Y'all should come across your newly-created projection on that dashboard.
Add together Firebase SDK to React Native app
Using react-native-firebase
version v or beneath, since it was a monorepo, all Firebase dependencies were available from a single module to employ in a React Native app. However, with version half dozen you have to install dependencies based on Firebase features that you lot desire to use. For example, in the electric current app, to use storage, you are going to install the core app packet equally well equally storage package. As said that the core module @react-native-firebase/app
is always required. Open up a final window to install these dependencies.
yarn add together @react-native-firebase/app @react-native-firebase/storage
Add Firebase credentials to your iOS app
Firebase provides a GoogleService-Info.plist
file that contains all the API keys likewise every bit other credentials needed for iOS devices to authenticate the correct Firebase project. To admission these credentials, go to back to the "Firebase console", and from the dashboard screen of your Firebase project, open "Project settings" from the side menu. Go to the "Your apps" section and click on the icon iOS
to select the platform. Enter the application details and click on the "Register app". And so download the GoogleService-Info.plist
file, as shown beneath. Open Xcode, and then open up the /ios/uploadStorageDemo.xcodeproj
file. Correct-click on the project name and choose the Add Files option—then select the appropriate file to add to this projection. Side by side, open ios/uploadStorageDemo/AppDelegate.yard
and add the following header.
#import <Firebase.h>
Inside the didFinishLaunchingWithOptions
method, add the following configure method.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([FIRApp defaultApp] == nil) { [FIRApp configure]; }
Become back to the last window to install pods.
cd ios/ && pod install # afterwards pods are installed cd ..
Make sure you build the iOS app before running it. Open
npx react-native run-ios
Add Firebase credentials to your Android app
For Android apps, Firebase provides a google-services.json
file that contains all the API keys equally well as other credentials needed for Android devices to authenticate the correct Firebase project. Go to the "Your apps" section and click on the icon Android
to select the platform. Download the google-services.json
file. Now re-create the downloaded JSON file in React Native projection at the following location: /android/app/google-services.json
. Open up your android/build.gradle
file to add together the following snippet.
dependencies { // ... classpath 'com.google.gms:google-services:iv.2.0' }
Next, open up android/app/build.gradle
file, and at the very bottom of this file, add the post-obit snippet.
apply plugin: 'com.google.gms.google-services'
Lastly, make sure you build the Android app.
npx react-native run-android
Using React Native Image Picker
In this department, permit us start edifice the app. Start past opening the file UploadScreen.js
and import the following statements.
import React, { useState } from 'react'; import { View, SafeAreaView, Text, TouchableOpacity, StyleSheet, Platform, Warning, Epitome } from 'react-native'; import ImagePicker from 'react-native-epitome-picker'; import storage from '@react-native-firebase/storage'; import * every bit Progress from 'react-native-progress';
Within the role component UploadScreen
create iii state variables. The first, paradigm
is going to exist used to shop the URI of the source of the image. The same URI will be then used to brandish the prototype picked by the user and to upload the epitome to the Firebase cloud storage. The second country variable is uploading
that is going to be imitation
default. This is going to go along track of whether the image is uploading to the cloud storage or non. The third variable transferred
is going to track the progress of the image being upload.
export default function UploadScreen() { const [epitome, setImage] = useState(nothing); const [uploading, setUploading] = useState(false); const [transferred, setTransferred] = useState(0); //... }
Add together a helper method called selectImage
that is going to utilize the react-native-image-picker
to select an epitome from the device's library and brandish the image picker itself. Also, ascertain an options
object to fix properties like maximum width and height besides every bit a default path. This options
object is going to exist passed equally the first parameter in ImagePicker.showPicker()
method that is going to return a callback which sends the response
object. Using this callback, the path of the image land variable tin can exist gear up. You lot can discover the consummate set of options to pass in the official docshither.
const selectImage = () => { const options = { maxWidth: 2000, maxHeight: 2000, storageOptions: { skipBackup: true, path: 'images' } }; ImagePicker.showImagePicker(options, response => { if (response.didCancel) { panel.log('User cancelled prototype picker'); } else if (response.error) { console.log('ImagePicker Mistake: ', response.fault); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { const source = { uri: response.uri }; console.log(source); setImage(source); } }); };
Define some other helper method called uploadImage
that is going to upload the image to the cloud storage. This method is going to be asynchronous by default and then let usa async-await
syntax. Also, when this method triggers, update the value of uploading
to true and transferred
to 0 to track the progress of the image being upload to the storage. Using storage
from Firebase you tin trigger the image upload. It is important to annotation that the filename
has to be passed as a reference as well as the epitome URI using putFile
in the guild described beneath. Later the image has uploaded to the storage, display an alarm method using react native component Warning
and prepare state variables to default as shown below.
const uploadImage = async () => { const { uri } = image; const filename = uri.substring(uri.lastIndexOf('/') + 1); const uploadUri = Platform.Os === 'ios' ? uri.replace('file://', '') : uri; setUploading(true); setTransferred(0); const chore = storage() .ref(filename) .putFile(uploadUri); // set progress state task.on('state_changed', snapshot => { setTransferred( Math.round(snapshot.bytesTransferred / snapshot.totalBytes) * 10000 ); }); try { await job; } take hold of (east) { console.mistake(e); } setUploading(false); Alert.alert( 'Photo uploaded!', 'Your photograph has been uploaded to Firebase Deject Storage!' ); setImage(null); };
Here is the complete JSX returned from this functional component. The progress that you are going to bear witness in the app is going to be in the form of a bar.
export default function UploadScreen() { //... rest of the code render ( <SafeAreaView style={styles.container}> <TouchableOpacity style={styles.selectButton} onPress={selectImage}> <Text manner={styles.buttonText}>Pick an image</Text> </TouchableOpacity> <View way={styles.imageContainer}> {prototype !== aught ? ( <Prototype source={{ uri: image.uri }} style={styles.imageBox} /> ) : zippo} {uploading ? ( <View style={styles.progressBarContainer}> <Progress.Bar progress={transferred} width={300} /> </View> ) : ( <TouchableOpacity fashion={styles.uploadButton} onPress={uploadImage}> <Text fashion={styles.buttonText}>Upload image</Text> </TouchableOpacity> )} </View> </SafeAreaView> ); }
Here are the complete styles for the in a higher place component.
const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#bbded6' }, selectButton: { borderRadius: v, width: 150, tiptop: l, backgroundColor: '#8ac6d1', alignItems: 'centre', justifyContent: 'eye' }, uploadButton: { borderRadius: 5, width: 150, height: 50, backgroundColor: '#ffb6b9', alignItems: 'center', justifyContent: 'center', marginTop: twenty }, buttonText: { colour: 'white', fontSize: 18, fontWeight: 'bold' }, imageContainer: { marginTop: xxx, marginBottom: 50, alignItems: 'center' }, progressBarContainer: { marginTop: 20 }, imageBox: { width: 300, acme: 300 } });
Hither is the output y'all are going to get. To verify that the image is stored in the cloud storage, go back to the Firebase console dashboard and become to the storage section.
Conclusion
Cheers for following up this tutorial. Using react-native-firebase
version 6 brings benefits like less configuration and focus more on developing the app. Do refer thedocsof react-native-progress
for more data on customizing the progress bar. You can also check this interesting website on cloud storage reviews.
Next Steps
Now that yous have learned nearly resources to learn React Native development, hither are some other topics you tin expect into
- Firebase — Push notifications|Firebase storage
- How To in React Native —WebView| Gradient| Camera| Adding GIF| Google Maps | Redux | Debugging | Hooks| Dark style | Deep-link | GraphQL | AsyncStorage | Offline |Chart | Walkthrough | Geolocation | Tinder swipe | App icon | Balance API
- Payments —Apple Pay|Stripe
- Authentication —Google Login|Facebook login|Phone Auth|
- Best Resource –App idea|Podcast |Newsletter|App template
If y'all need a base to start your next React Native app, you can brand your next crawly app usingmanyReact Native template.
heistpubleausing98.blogspot.com
Source: https://instamobile.io/mobile-development/react-native-firebase-storage/
0 Response to "Upload Photo With React Native and Firebase"
Post a Comment