Open In App

How to Upload and Preview an Image in React Native ?

Image uploading and previewing are widespread in mobile apps. With the Expo ImagePicker package, React Native makes this work easier. Uploading and previewing photographs is a common feature in Android and iOS applications, especially in the user profile section. This feature allows users to submit an image and view a preview of it. In this article, we are going to see how we can add image upload functionality and preview it on the screen.

To begin, you will be required to configure your development setup. This entails the installation of Node.js, which serves as the runtime environment for executing JavaScript code beyond the confines of a web browser.



Prerequisites:

Steps to Create React Native Application:

Step 1: Set Up the Development Environment​. Install Expo CLI globally by running this command:

npm install -g expo-cli​

Step 2: Create React Native Application With Expo CLI



expo init image-upload

Step 3: Navigate to the project directory by using this command:

cd image-upload 

Project Structure

Step 4: Install the required dependencies by running:

npm install expo-image-picker

Approach

Example: In this example, we will show how to upload an Image and Preview it using React Native.




import React, { useState } from "react";
import { View, Text, Image, TouchableOpacity, 
    StyleSheet, Alert } from "react-native";
import * as ImagePicker from "expo-image-picker";
  
export default function App() {
  
    // Stores the selected image URI
    const [file, setFile] = useState(null);
  
    // Stores any error message
    const [error, setError] = useState(null);
  
    // Function to pick an image from 
    //the device's media library
    const pickImage = async () => {
        const { status } = await ImagePicker.
            requestMediaLibraryPermissionsAsync();
  
        if (status !== "granted") {
  
            // If permission is denied, show an alert
            Alert.alert(
                "Permission Denied",
                `Sorry, we need camera 
                 roll permission to upload images.`
            );
        } else {
  
            // Launch the image library and get
            // the selected image
            const result =
                await ImagePicker.launchImageLibraryAsync();
  
            if (!result.cancelled) {
  
                // If an image is selected (not cancelled), 
                // update the file state variable
                setFile(result.uri);
  
                // Clear any previous errors
                setError(null);
            }
        }
    };
  
    return (
        <View style={styles.container}>
            <Text style={styles.header}>
                Add Image:
            </Text>
  
            {/* Button to choose an image */}
            <TouchableOpacity style={styles.button}
                onPress={pickImage}>
                <Text style={styles.buttonText}>
                    Choose Image
                </Text>
            </TouchableOpacity>
  
            {/* Conditionally render the image 
            or error message */}
            {file ? (
                // Display the selected image
                <View style={styles.imageContainer}>
                    <Image source={{ uri: file }}
                        style={styles.image} />
                </View>
            ) : (
                // Display an error message if there's 
                // an error or no image selected
                <Text style={styles.errorText}>{error}</Text>
            )}
        </View>
    );
}
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        padding: 16,
    },
    header: {
        fontSize: 20,
        marginBottom: 16,
    },
    button: {
        backgroundColor: "#007AFF",
        padding: 10,
        borderRadius: 8,
        marginBottom: 16,
        shadowColor: "#000000",
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.4,
        shadowRadius: 4,
        elevation: 5,
    },
    buttonText: {
        color: "#FFFFFF",
        fontSize: 16,
        fontWeight: "bold",
    },
    imageContainer: {
        borderRadius: 8,
        marginBottom: 16,
        shadowColor: "#000000",
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.4,
        shadowRadius: 4,
        elevation: 5,
    },
    image: {
        width: 200,
        height: 200,
        borderRadius: 8,
    },
    errorText: {
        color: "red",
        marginTop: 16,
    },
});

Step 5: To run React Native use the following command in the Terminal/CMD:

npx expo start

To run on Android:

npx react-native run-android

To run on ios:

npx react-native run-ios

Output:

How to Upload an Image and Preview it using React Native


Article Tags :