Open In App

How to upload image and Preview it using ReactJS ?

Last Updated : 21 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In React upload and preview images improves 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. createObjectURL().

Prerequisite:

Approach:

To upload 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 URL.createObjectURL() method and store in the useState variable named file. Display the image as preview using the html img tags with the file url in the src prop.

Steps to Create React Application :

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

npm create-react-app project

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

cd project

Project Structure:

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

Javascript




// Filename - 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} />
            <img src={file} />
        </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.


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

Similar Reads