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

Hey👋, It's me Utsav, I craft code and love to write what I learn.
Search for a command to run...

Hey👋, It's me Utsav, I craft code and love to write what I learn.
Helpful ♥️
Introduction This year, I had the incredible opportunity to attend the GNOME Asia Summit 2024 in Bengaluru as a contributor. Looking back, it feels like a full-circle moment. Last year, I was a volunteer at GNOME Asia Summit 2023, which was held in N...

Have you ever struggled to write a good Git commit message? I know I have! That’s why I created gc—a CLI tool powered by AI to help you write clear, meaningful commit messages without any hassle. Why did I build gc? The idea for gc came from a commo...

Struggling with clunky KYC procedures? AI-KYC is the answer! Our intelligent system simplifies and speeds up verification, turning a complex task into an effortless one. Revolutionize your KYC experience now! 🚀 Meet our Team Hi! I’m Utsav Bhattarai ...

Apexa - Your All-in-One Creative Hub: Explore Smart Comment Analysis & Summaries, Instant Image Generation, and Effortless Content Ideas

Unlocking the code: My Journey Through Hacktoberfest 2023, where collaboration meets innovation, challenges become opportunities, and open source unites us all. Let's get started! Overview🚀 Back in 2022, I was introduced to Hacktoberfest, but being ...

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⚡

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🤩