Skip to content
Related Articles

Related Articles

How to upload image and Preview it using ReactJS ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 03 Mar, 2022

In this article, we will learn how we can simply upload a photo from our local device to our React Project. We can achieve this by doing a static method URL. createObjectURL().

The method URL. createObjectURL() takes an object and returns a URL representing the object used as a parameter.

Prerequisite:

Creating React Application:

Step 1: Create the react project folder, for that open the terminal, and write the command npm create-react-app folder name, if you have already installed create-react-app globally. If you haven’t then install create-react-app globally by using the command npm -g create-react-app or can install locally by npm i create-react-app.

npm create-react-app project

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

cd project

Project Structure: It will look like this:

We are creating a state name file using React-hook useState that will store the file. We are creating an input field that will take a file as the input.

We are creating an onChange function naming handleChange that stores URL string generated for the image we have uploaded through URL. createObjectURL().

If we do console.log like this:

console.log(e.target.files)

We will get the following output:

Hence, in our file state, we will store only files[0] that will only contain the name of the file we have uploaded. We are storing the data in our file state through the function handleChange.

Example: After, that we are putting that string stored in the App.js file in the src attribute of img tag to display it.

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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!