How to upload Image and preview it using reactjs

Share the post

Hello Everyone, Today we will discuss How to upload Image and preview it using reactjs. Select the image using choose file & preview it using reactjs.

In the Previous ReactJS tutorial, We had discussed How to upload a video & preview it using reactjs. Now, in this example, We will take html input & choose the image file. Then we will generate an object URL & preview that selected image using reactjs.

So, Let’s Start…

Example for How to upload Image and preview it using reactjs

  • Step1: Create a new React Project
  • Step2: Write the code
  • Step3: Run the React Application
  • Step4: Output

Step1: Create a new React Project

We need to create a new ReactJS Project. Use the following command to create a new project in ReactJS.

npx create-react-app myapp

Now, go to navigate to the project path as shown below

cd myapp

We will open this project in the Visual Studio Code editor using the following command.

code .

Step2: Write the Code

Now, We have to take one input to select an image file & one img HTML tag to display that selected image. Please see the below App.js for reference.

Full App.js

import React, { useState } from "react";

const App = () => {
  const [imagePath, setImagePath] = useState(null);
  const handleImageUpload = (event) => {
    setImagePath(URL.createObjectURL(event.target.files[0]));
  };
  return (
    <>
      <div>
        <div>
          <input type="file" onChange={handleImageUpload} />
        </div>
        <div>
          <p>Display selected Image</p>
          <img src={imagePath} width="100%" height="100%" />
        </div>
      </div>
    </>
  );
}

export default App;

Step3: Run the React Application

Now, Run the React Application using the following command.

npm run start

Step4: Output

Now, We can check the output in the browser. Please see the below output.

How to upload Image & preview it using reactjs

Leave a Comment

Exit mobile version