Tue May 02 2023
How to preview a chosen image from local disk in React
Today we will create a component in React, where we will select an image from the local disk and preview the image. We will style our file <input /> with the styling from this guide.
Final result
This is what it will look like when we are done with this guide
Our component
Let's create our React component, ImagePreviewer.tsx (or .jsx).
import { useState } from "react"; import style from "./ImagePreviewer.module.scss"; import { ChangeEvent } from "react"; export const ImagePreviewer = () => { const [selectedFileName, setSelectedFileName] = useState<string>(""); const [previewImg, setPreviewImg] = useState<any>(); const onFileChoosen = (event: ChangeEvent<HTMLInputElement>) => { const file = event?.target?.files?.[0]; if (file) { setSelectedFileName(file.name); const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = (ev) => setPreviewImg(ev?.target?.result); } }; const renderPreview = () => { if (selectedFileName && previewImg) { return ( <div className={style.previewContainer}> <span className={style.nameLabel}>{selectedFileName}</span> <img className={style.previewImg} alt="preview" src={previewImg} /> </div> ); } return null; }; return ( <div className={style.imagePreviewer}> {renderPreview()} <label className={style.chooseButton} htmlFor="fileInput"> Choose image <input id="fileInput" className={style.input} onChange={onFileChoosen} type="file" accept="image/*" /> </label> </div> ); };
There we go. Now, let me explain the important parts
- onFileChoosen() - Our callback function that will be called when we have selected a file. We will set our state variables from here. The selectedFileName will get our file name that we just selected, and the previewImg will get a base64 string from our FileReader after we have loaded it with readAsDataURL() function.
- renderPreview() - Will render our image and file name if the variable are set.
Now, let's style it
.imagePreviewer { display: flex; flex-direction: column; border: 1px solid #efebeb; border-radius: 8px; width: 300px; padding: 1rem; .previewContainer { display: flex; flex-direction: column; padding: 1rem 0; gap: 1rem; .previewImg { border-radius: 8px; height: 120px; width: 120px; } .nameLabel { font-size: 11px; font-style: italic; } } .chooseButton { display: flex; font-size: 12px; font-weight: bold; justify-content: center; padding: 10px 0; cursor: pointer; background-color: #b17e07; color: white; border-radius: 4px; width: 120px; .input { display: none; } } }
There we go. Now it is done, and can be called like this from wherever you need it
import { ImagePreviewer } from "components/ImagePreviewer/ImagePreviewer"; <ImagePreviewer />;
Outro
In this tutorial, we created a component that selects an image file and then, with the help of FileReader in JavaScript, previews the image.
I hope you liked this guide, and thanks for reading.
All the best,
Tue May 02 2023
See all our articles