Access Camera and Camera Roll

In this section, you’re going to add the functionality of accessing the Camera and Camera Roll by defining three different handler functions in the App component. Make sure you’re inside the file App.js . First, import the following statement since this section is going to make use of Firebase's storage, and the uuid module to create a unique referent to each image.

Next, modify the initial state of the object to add the following for the final time:

To enable both of these functionalities in the current app, let’s leverage another Expo module called expo-image-picker . First, import the module after the rest of the import statements.

Expo documentation has the best definition of what this module is used for. Take a look:

[Image Picker] Provides access to the system’s UI for selecting images and videos from the phone’s library or taking a photo with the camera.

That’s all you need right now. Define the first function, takePhoto , which is going to access the phone's Camera to select a photo.

The asynchronous method ImagePicker.launchCameraAsync() accepts two arguments:

allowsEditing shows the UI to edit the image after it’s clicked. Mostly used to crop images.

shows the UI to edit the image after it’s clicked. Mostly used to crop images. aspect is an array to maintain a consistent aspect ratio if allowsEditing is set to true.

Similarly, ImagePicker.launchImageLibraryAsync() is used with the same set of arguments to access the Camera roll.

Both of these asynchronous functions, return the uri of the image selected (among other arguments that you can view in the official docs here). Lastly, both of these methods are calling another callback— handleImagePicked —after their job is done. This method contains the logic of how to handle the image after it’s clicked or picked from the Camera roll.

Initially, set the state of uploading to true. Then, if an image is selected, call the custom method uploadImageAsync (which will be defined at the end of this section) and pass the URI of the image selected. This will also set the value of the image from the state object to the URL of the uploaded image. Lastly, set the state of uploading in the finally block back to false if the results are positive and the image has uploaded without any errors.

The custom method uploadImageAsync has to be defined outside the App component. It will upload the image by creating a unique image ID or blob with the help of uuid . It uses xhr to make an Ajax call to send a request to Firebase storage to upload the image.

Note that the source code for accessing and uploading an image to Firebase is taken from this example of using Expo with Firebase.

Now you can add both the functions, pickImage and takePhoto , as the value of onPress props for the corresponding icons.

Here’s an example of accessing Camera roll.