DEV Community

Cover image for React Native Firebase Storage

React Native Firebase Storage

What is React Native Firebase Storage

Cloud Storage is designed to help you quickly and easily store and distribute user-generated content, such as photos and videos. Firebase Storage is truly a revolutionary tool in the lives of developers like me. The API is really simple and easy to set up. Now let's get back to the heart of the matter

How to Save Images and Video to Firebase Storage with React Native

To save images and photos to firebase Storage. Nothing's easier. Consider that a user must be able to put his profile picture, so it will have to be saved on the ohh🤦‍♂️ database. Hey no worries 😂 you'll figure it all out. Let's go !!!!! First of all you need to be able to select a photo, I use react-native-image-crop-picker. the package is available on NPM ==> available here

After installation let's kiss the code😰.

To save an image , you must create the image reference. A reference is a local pointer to a file in your bucket. This can either be a file that already exists or a file that does not yet exist. To create a reference, use the refméthode: it's just the url of your image it's simple.

Creation of the reference

import React from 'react'
import storage from '@react-native-firebase/storage';

export default function UploadImage() {
const reference = storage().ref('url or name_of_file');
}
Enter fullscreen mode Exit fullscreen mode

**
Now let's use ImageCropPicker function to choose our photo.
Here's how to do it.**

import React from 'react'
import storage from '@react-native-firebase/storage';
import ImagePicker from 'react-native-image-crop-picker';
export default function UploadImage() {
    //function for choose the image with image-crop-picker
    const choose_photo = () => {
        ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true
        }).then(image => {
            console.log(image);
            setImage(image.path)
            sheet.current.close()

        });
    }

    //Ref of our image
   const reference = storage().ref('url or name_of_file');

}
Enter fullscreen mode Exit fullscreen mode

Now we need to create React Hook with useState to take the selected image and display it on our application.

const [image, setImage] = React.useState(null);
Enter fullscreen mode Exit fullscreen mode


`

Now let's create the Button to choose the image and display it

`

  return (
        <view style={styles.container}>
            <View style={styles.container_images}>
                <TouchableOpacity onPress={() => choose_photo()}> 
                    {image && <Image source={{ uri: image }} 
             style={styles.image_picker} />}
                    {!image && <Image source={require('../assets/moi.jpg')} 
                  style={styles.image_picker} />}
                </TouchableOpacity>
            </View>
        </view>
    )

}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },

    image_picker: {
        width: 180,
        height: 180,
        borderRadius: 90
    },
    container_images: {
        alignItems: 'center',
        marginTop: hp('1%')
    }
})
Enter fullscreen mode Exit fullscreen mode


`

Here is the full code

`

import React from 'react'
import storage from '@react-native-firebase/storage';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'
import ImagePicker from 'react-native-image-crop-picker';
export default function UploadImage() {
    //function for choose the image with image-crop-picker
    const choose_photo = () => {
        ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true
        }).then(image => {
            console.log(image);
            setImage(image.path)
            sheet.current.close()

        });
    }

    //Ref of our image
   const reference = storage().ref('url or name_of_file');
    //React Hook useState
    const [image, setImage] = React.useState(null);

    return (
        <view style={styles.container}>
            <View style={styles.container_images}>
                <TouchableOpacity onPress={() => choose_photo()}> 
                    {image && <Image source={{ uri: image }}
                     tyle={styles.image_picker} />}

                    {!image && <Image source={require('../assets/moi.jpg')}
                     style={styles.image_picker} />}
                </TouchableOpacity>
            </View>
        </view>
    )

}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },

    image_picker: {
        width: 180,
        height: 180,
        borderRadius: 90
    },
    container_images: {
        alignItems: 'center',
        marginTop: hp('1%')
    }
})


Enter fullscreen mode Exit fullscreen mode


`
Now let's save the image to firebase Storage

For this we create another function that we will link with our reference, this is the url of the image.
I move the constant reference inside the function
save_photo

`

        const savephoto = async () => {
        const aploaduri = image;
        let filename = 
        aploaduri.substring(aploaduri.lastIndexOf('/') + 1);
        const reference = storage().ref(filename)
        const task = reference.putFile(aploaduri)
        //set  transferred state
        task.on('state_changed', taskSnapshot => {
            console.log(`${taskSnapshot.bytesTransferred} 
         transferred out of 
              ${taskSnapshot.totalBytes}`);
        });

        try {
            await task;
            const url = await reference.getDownloadURL()
            Alert.alert('Your image is saved! smile😇')
            return url
        }
        catch (e) {
            console.log(e)
            return null
        }

    }
Enter fullscreen mode Exit fullscreen mode


`

Now just call the save_photo function with the onPress button and boom

Here is the final code

`

import React from 'react'
import storage from '@react-native-firebase/storage';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'
import ImagePicker from 'react-native-image-crop-picker';
export default function UploadImage() {
    //function for choose the image with image-crop-picker
    const choose_photo = () => {
        ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true
        }).then(image => {
            console.log(image);
            setImage(image.path)
            sheet.current.close()

        });
    }
    //React Hook useState
    const [image, setImage] = React.useState(null);

    const savephoto = async () => {
        const aploaduri = image;
        let filename = aploaduri.substring(aploaduri.lastIndexOf('/') + 1);
        const reference = storage().ref(filename)
        const task = reference.putFile(aploaduri)
        //set  transferred state
        task.on('state_changed', taskSnapshot => {
            console.log(`${taskSnapshot.bytesTransferred} transferred out of 
              ${taskSnapshot.totalBytes}`);
        });

        try {
            await task;
            const url = await reference.getDownloadURL()
            Alert.alert('Your image is saved! smile😇')
            return url
        }
        catch (e) {
            console.log(e)
            return null
        }

    }

    return (
        <view style={styles.container}>
            <View style={styles.container_images}>
                <TouchableOpacity onPress={() => choose_photo()}>
                    {image && <Image source={{ uri: image }} 
             style={styles.image_picker} />}
                    {!image && <Image source={require('../assets/moi.jpg')}
             style={styles.image_picker} />}
                </TouchableOpacity>
            </View>

            <View>
                <TouchableOpacity onPress={() => savephoto()}>
                    <Text>save</Text>
                </TouchableOpacity>
            </View>
        </view>
    )

}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },

    image_picker: {
        width: 180,
        height: 180,
        borderRadius: 90
    },
    container_images: {
        alignItems: 'center',
        marginTop: hp('1%')
    }
})
Enter fullscreen mode Exit fullscreen mode


`

Thank you for reading my article, subscribe and follow me on social networks.

Top comments (0)