In the beginning, the web was only text. And it was somehow boring. It didn't take too long for the introduction of images (one of the best types of content) on the web. Today we are not going to talk about how to upload images. We are going to look at how to preview an image on the frontend before uploading it to the server. Hope you don't get bored.
I'm using React js in this article.
Let's get started:
Firstly create a react js project by using create-react-app or another approach you want.
Edit App.js
and insert this code.
Update handleFile
function with these codes:
let tempFile = e.target.files[0];
const reader = new FileReader();
reader.addEventListener(
"load",
function () {
setfile(reader.result);
},false);
if (tempFile) {
reader.readAsDataURL(tempFile);
}
I added a few CSS in App.css
form {
width: 60%;
margin: 5rem auto;
}
form div.output {
border: 1px solid rgb(218, 213, 213);
margin-top: 20px;
padding: 10px;
max-width: 50%;
}
.output img {
max-width: 100%;
}
Finally, our app has a new look.
Thanks for reading this article until this line. If you want the code of the app, find it here. You can also test it here. To read more about FileReader visit this site.
You can find me anytime on Twitter and Instagram. Have a nice day😍😍
Top comments (8)
wow! This was helpful
nice to hear that it helped
amazing congz
thanks 😍😍
Too helpful.
nice to hear 😍
kudos
appreciated