Open In App

How to Upload and Preview an Image in React Native ?

Last Updated : 01 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • Installation: In this article, we will use the Expo CLI edition, which offers a more seamless experience for executing your React Native apps. Proceed sequentially through the provided instructions to establish your React native ecosystem.
  • Expo is a JavaScript and React-based platform that enables developers to create cross-platform mobile applications for iOS, Android, and the web using a unified codebase. This free and open-source framework offers a range of tools and services that streamline the mobile app development process, empowering developers to construct top-notch applications.

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

React-Native-Project-Structure

Step 4: Install the required dependencies by running:

npm install expo-image-picker

Approach

  • We’ll use React Native along with the Expo framework and Expo ImagePicker module to solve this problem.
  • The state variables ‘file’ and ‘error’ are created inside the ‘App’ method using ‘useState’ to store the URI of the selected image and any error messages.
  • The ‘pickImage’ function solicits authorization before locating the image URI. Three elements make up the UI rendering: a container, a header, and a button. The ‘pickImage’ function is activated by pressing the button.

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

  • App.js

Javascript




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

How to Upload an Image and Preview it using React Native



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads