DEV Community

Cover image for Image Live Preview app with React.js
Oreste Abizera
Oreste Abizera

Posted on

Image Live Preview app with React.js

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.
Alt Text

Edit App.js and insert this code.

Alt Text
The result will be:
Alt Text

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);
}
Enter fullscreen mode Exit fullscreen mode

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%;
}
Enter fullscreen mode Exit fullscreen mode

Finally, our app has a new look.
Alt Text

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)

Collapse
 
blessinghirwa profile image
Blessing Hirwa

wow! This was helpful

Collapse
 
oreste profile image
Oreste Abizera

nice to hear that it helped

Collapse
 
muhodari profile image
Muhodari Sage

amazing congz

Collapse
 
oreste profile image
Oreste Abizera

thanks 😍😍

Collapse
 
sauve2003 profile image
Sauvé Jean-Luc

Too helpful.

Collapse
 
oreste profile image
Oreste Abizera

nice to hear 😍

Collapse
 
ishgervais profile image
Gervais Ishimwe

kudos

Collapse
 
oreste profile image
Oreste Abizera

appreciated