How to Upload Image and Preview it Using ReactJS?

Last Updated : 18 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In React, uploading and previewing images improve the user experience of the application. It's typical for online apps to provide image upload capability that enables users to choose and upload photographs. We simply upload a photo from our local device to our React Project and preview it using a static method URL.

Prerequisite

Approach for the Image Upload and Preview it

To upload an image and preview it using React JS we will use the HTML file input for the image input. After taking input the image URL is created using the URL.createObjectURL() method and stored in the state variable named file. Display the image as a preview using the HTML img tags with the file URL in the src prop.

Steps to Create a React Application

Step 1: Initialize a React App using this command in the terminal.

npm create vite@latest project

Step 2: After creating your project directory(i.e. project), move to it by using the following command.

cd project

Project Structure:

Project_Structure
Project Structure

Example: This example implements upload and preview image using the createObjectURL method and HTML file input and img tag.

JavaScript
//App.js
import React, { useState } from "react";
function App() {
    const [file, setFile] = useState();

    function handleChange(e) {
        console.log(e.target.files);
        setFile(URL.createObjectURL(e.target.files[0]));
    }

    return (
        <div className="App">
            <h2>Add Image:</h2>
            <input type="file" onChange={handleChange} />
            {file && <img src={file} alt="Uploaded preview" />}
        </div>
    );
}

export default App;

Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.

In this code:

  • Imports React and useState: Imports React and useState for state management in the component.
  • State for File: Creates a state variable file to store the URL of the uploaded image.
  • handleChange Function: When a file is selected, it updates the file state with the image's URL using URL.createObjectURL().
  • File Input: Renders an input field for the user to select an image file.
  • Conditional Image Display: Only shows the image preview if a file is selected (i.e., file is not empty).

Benefits of the Image Upload and Preview It

  • Enhances user experience by providing an image preview immediately after upload.
  • Offers real-time feedback to users for image verification.
  • Simplifies image handling in React applications using state and URL object.
  • Easily integrates into various applications like social media or e-commerce.
  • Provides a simple and minimal code solution for image upload and preview.

Next Article

Similar Reads