React Native Firebase Storage
Published: 2021-01-08 00:01:30

**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](https://github.com/ivpusic/react-native-image-crop-picker)

**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**

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

export default function UploadImage() {
const reference = storage().ref('url or name_of_file');
}
```
**
Now let's use ImageCropPicker function to choose our photo.
Here's how to do it.**

```javascript
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');

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

````javascript
const [image, setImage] = React.useState(null);
````

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

````javascript
  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%')
    }
})
````

Here is the full code

````javascript
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%')
    }
})


````
**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

````javascript
        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
        }

    }
````

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

**Here is the final code**

````javascript
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%')
    }
})
````

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