How to display a image selected from input file in react?

How to display a image selected from input file in react?

Overview

Sometimes, We want to display image selected from input file in React but we stuck following traditional way to do that. So In this article, We will learn to do so with easy way.

Let's get started⚡

Let'SGetStartedGIF.gif

How to do?

To display a image selected from file input, we can call the URL.createObjectURL with the selected file object and set the returned value as the value of the src prop of the img element.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [pic, setPic] = useState();

  const getImg = (e) => {
    const [file] = e.target.files;
    setPic(URL.createObjectURL(file));
  };

  return (
    <div>
      <input type="file" onChange={getImg} />
      <img src={pic} alt="img" />
    </div>
  );
}

We define the pic state which we use as the value of the src prop of the img element.

Next, we define the getImg function that takes the file from the e.target.files property via destructuring.

Then we call URL.createObjectURL on the file to return a URL that we can use as the value of pic.

And we call setPic with the returned URL string to set that as the value of pic.

In this way, We can select the image from input easily🔥.

Connect me through👉 @utsavbhatrai007

Thanks for reading🤩