Monday, February 20, 2023

How to Upload Images to Firebase from a React Native App

How to Upload Images to Firebase from a React Native App

If you're building a mobile or web application, you'll typically need some kind of hosting service to manage the application data, upload and manage files, and possibly carry out social authentication with third-parties like Google, Facebook and GitHub.

Firebase is a cloud-based hosting platform that allows you to do all of that, plus so much more. Firebase Storage is used to securely upload to your Firebase apps, and download them into the apps.

In this post, you'll build a React Native application with the ability to upload images to Firebase Storage.

Firebase Setup

If you don't have a Firebase account yet, you can create one at the Firebase home page. Once your account is set up, go to your Firebase console, and click the Add Project button to add a new project.

Enter your project details and click the Create Project button when done. On the next page, select the web option (that is, the </> icon). This'll lead you to Add Firebase to your web app page.

Firebase setupFirebase setupFirebase setup
Firebase setup

Provide a nickname for your app, then click Register app. In the following page, you’ll be provided with the Firebase SDK installation command and the details you need to include in your app’s config file to connect the it with Firebase.

SDK detailsSDK detailsSDK details
SDK details

Be sure to copy all of this configuration to an accessible location as you'll use it later.

Create the storage

  1. Go to your project's dashboard page inside Firebase
  2. On the sidebar, navigate to the Build > Storage page
  3. Click on Get Started, select start in test mode, then click Next

Next settingNext settingNext setting
Next setting
  • In the following page, set the cloud storage location to us-west-2 (or any other location, doesn’t matter).
  • Click Next to provision the storage.

That’s all for Firebase. Let’s now create the UI for uploading the image from our React Native app.

Developing the React Native App

Prerequisites

To follow this tutorial, you’ll need:

  • At least a basic understanding of React Native
  • Set up Expo or React Native CLI on your local dev machine
  • If you're using the React Native CLI, you need to have XCode or Android studio installed to run the emulator.
  • Install firebase with npm install firebase.

Creating an image uploader

Open your React Native project with Visual Studio Code (or another IDE). Go inside the /components folder and create a new file called UploadScreen.js.

Open the file and importing the following:

1
  import React, {useState} from 'react'
2
    import {View, StyleSheet, Image, Text, TouchableOpacity, SafeAreaView, Alert} from 'react-native'
3
    import * as ImagePicker from 'expo-image-picker'
4
    import {firebase} from '../config' 

Next, create an UploadScreen component function and return an empty <SafeAreaView> for now. Also export the function at the file bottom:

1
const UploadScreen = () => {
2
    return(
3
        <SafeAreaView>
4
          // view will go here

5
        </SafeAreaView>

6
    )
7
}
8
export default UploadScreen;

Just above the return statement, create the image and loading state and set them to null to false initially:

1
   const [image, setImage] = useState(null)
2
   const [uploading, setUploading] = useState(false) 

Create the function pickImage. When invoked, this function launches your device’s image library so you can pick your image. After the image is retrieved, we store it in the state by calling setImage:

1
    const pickImage = async () => {
2
        let result = await ImagePicker.launchImageLibraryAsync({
3
            mediaTypes: ImagePicker.MediaTypeOptions.All,
4
            allowsEditing: true,
5
            aspect: [4,3],
6
            quality: 1
7
        });
8
        const source = {uri: result.assets[0].uri}
9
        console.log(source)
10
        setImage(source)
11
    }; 

After picking an image, we then have to upload it to Firebase. The following function takes care of that when invoked:

1
    const uploadImage = async () => {
2
        setUploading(true)
3
        const response = await fetch(image.uri)
4
        const blob = response.blob()
5
        const filename = image.uri.substring(image.uri.lastIndexOf('/')+1)
6
        var ref = firebase.storage().ref().child(filename).put(blob)
7
        try {
8
            await ref;
9
        } catch (e){
10
            console.log(e)
11
        }
12
        setUploading(false)
13
        Alert.alert(
14
            'Photo uploaded!'
15
        );
16
        setImage(null);
17
    } 

With this code, we fetch the image address and retrieve the filename, which we then upload to Firebase. If successful, we activate an alert that says “Photo Uploaded” and reset the image state. However, if an error is encountered, we log it on the console.

Next, we display the view of our UploadScreen component. Copy and paste the following code inside the return() statement of the UploadScreen function:

1
<SafeAreaView style={styles.container}>
2
  <TouchableOpacity style={styles.selectButton} onPress={pickImage}>
3
    <Text style={styles.btnText}>Pick an Image</Text>

4
  </TouchableOpacity>   

5
  <View style={styles.imageContainer}>
6
   {image && <Image source= style=/>}            

7
  <TouchableOpacity style={styles.uploadButton} onPress={uploadImage}>
8
      <Text style={styles.btnText}>Upload Image</Text>

9
  </TouchableOpacity>

10
  </View>            

11
</SafeAreaView>

In the code above we define two buttons:

  • One for picking an image (clicking this button invokes pickImage)
  • The other for uploading the image to Firebase (pressing this invokes uploadImage)

Save the file changes.

Finally, go inside App.js and use the following code:

1
import * as React from 'react';
2
import { View, StyleSheet } from 'react-native';
3
import UploadScreen from './components/UploadScreen';
4
5
export default function App() {
6
  return (
7
    <View style={styles.container}>
8
      <UploadScreen />
9
    </View>

10
  );
11
}
12
13
const styles = StyleSheet.create({
14
  container: {
15
    flex: 1
16
  }

Save the file and check your device/emulator. You should find the following UI rendered on your device.

App final viewApp final viewApp final view
App final view

Click the Pick an Image button, select an image from your device and click Upload Image to upload it to Firebase.

Go to your Firebase storage and confirm that the image has been uploaded.

Image in FirebaseImage in FirebaseImage in Firebase
Image in Firebase

As you can see above, mine was uploaded successfully.

Now that you know how to upload an image, you can use that knowledge to build even more exciting projects with React Native. For instance, you can list your digital products or multiple premium access options (eg. amount of extra coins for a game) that can be unlocked via in-app purchases.  

Conclusion

As a developer, Firebase offers you lots of features, including file uploads with storage. Uploading files to Firebase requires you to set up a web application in Firebase. By the end of this process, you get the configurations for connecting your React Native app to Firebase.

I hope you found this article helpful. You can learn also how to upload images to Firebase from an Android app.


No comments:

Post a Comment