04-Apr-2023
.
Admin
Hi Guys,
Here, I will show you how to works react native image upload example. this example will help you how to upload image in react native. I’m going to show you about how to pick and upload image in react native. if you have question about how to use image upload in react native then I will give simple example with solution. Let's see bellow example how to implement image upload in react native.
Let's start following example:
Step 1: Download Project
In the first step run the following command to create a project.
expo init ExampleApp
Step 2: Install and Setup
You can install expo-image-picker to create Image upload:
expo install expo-image-picker
You can install react-native-paper:
npm install react-native-paper
Step 3: App.js
In this step, You will open the App.js file and put the code.
import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ToastAndroid, TouchableHighlight } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { Avatar, Button } from 'react-native-paper'
export default function Add() {
const [galleryPermission, setGalleryPermission] = useState(null);
const [imageUri, setImageUri] = useState(null);
const setToastMsg = msg => {
ToastAndroid.showWithGravity(msg, ToastAndroid.SHORT, ToastAndroid.CENTER);
}
const permisionFunction = async () => {
const imagePermission = await ImagePicker.getMediaLibraryPermissionsAsync();
console.log(imagePermission.status);
setGalleryPermission(imagePermission.status === 'granted');
if (imagePermission.status !== 'granted') {
setToastMsg('Permission for media access needed.');
}
}
useEffect(() => {
permisionFunction();
}, []);
const pick = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
quality: 1,
});
if (!result.cancelled) {
setImageUri(result.uri);
}
}
const removeImage = () => {
setImageUri(null);
setToastMsg('Image Removed');
}
return (
<View>
<View style={styles.innerContainer}>
<TouchableHighlight
onPress={pick}
underlayColor='rgba(0,0,0,0)'
>
<Avatar.Image
size={250}
source={{ uri: imageUri }}
/>
</TouchableHighlight>
</View>
<View style={[styles.innerContainer, { marginTop: 25, flexDirection: 'row' }]}>
<Button
mode='contained'
onPress={pick}
>
Upload Image
</Button>
<Button
mode='contained'
onPress={() => removeImage()}
style={{ marginLeft: 20 }}
>
Remove Image
</Button>
</View>
</View>
);
}
const styles = StyleSheet.create({
innerContainer: {
justifyContent: 'center',
alignItems: 'center',
marginTop: 100,
},
});
Run Project
In the last step run your project using the below command.
expo start
You can QR code scan in Expo Go Application on mobile.
Output :
It will help you...
#React Native