Preview File before uploading in React - Jatin Sharma (2024)

This article will explain how you can build a file previewer in React that works for images and videos. With this article's help, you can create your own and make support for other files.

Warning

This article only showcases the preview for an image and video.

Demo

Preview File before uploading in React - Jatin Sharma (1)

Creating FilePreviewer Component

First, let's just create a file components/FilePreviewer.js after that we need to import two things in that file useState and useRef.

components/FilePreviewer.js

import { useState, useRef } from "react";

Create a FilePreviewer function and export it as default.

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() {}

Now we render the UI for FIle Picker and in that there will be two buttons. One for selecting files and the other for clearing file input. Let's see how it's going to look like.

import { useState, useRef } from "react";export default function FilePreviewer() { return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input type="file" accept="image/*, video/*" hidden /> <button className="btn">Choose</button> <button className="btn">x</button> </div> <div className="preview"> <img src="" alt="" /> <video controls src=""></video> </div> </div> );}

This is just a starter code, I am going to add more things to this. First, understand what is going on. As you can see inside the btn-container class there are three inputs. One for selecting files but I won't use standard file input because when the user selects the file by standard input it shows the name of the file which I don't want (as shown in the following screenshot).

Preview File before uploading in React - Jatin Sharma (2)

Handling File Input button

I have created a new button to choose the file. To make this work we need to create a reference (ref) for file input. and handle the onChange event after that it will look something like this.

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() {  // FIle Picker Ref because we are not useing the standard File picker inputconst filePicekerRef = useRef(null); return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input ref={filePicekerRef} accept="image/*, video/*" onChange={previewFile} type="file" hidden /> <button className="btn">Choose</button> <button className="btn">x</button> </div> <div className="preview"> <img src="" alt="" /> <video controls src=""></video> </div> </div> );}

We will create the previewFile function in just a moment to handle the file selection.

Creating Custom File input Button

Now as I have hidden the original file input button we need to create our own.

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() { const filePicekerRef = useRef(null); return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input ref={filePicekerRef} accept="image/*, video/*" onChange={previewFile} type="file" hidden /> <button className="btn" onClick={() => filePicekerRef.current.click()}>Choose</button> <button className="btn">x</button> </div> <div className="preview"> <img src="" alt="" /> <video controls src=""></video> </div> </div> );}

In this, I am just triggering the file input button through ref when the user clicks this button.

File Selection

As we are handling two files (image and video). we need to create two states for that imagePreview and videoPreview.

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() { const [imagePreview, setImagePreview] = useState(null); const [videoPreview, setVideoPreview] = useState(null); const filePicekerRef = useRef(null); return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input ref={filePicekerRef} accept="image/*, video/*" onChange={previewFile} type="file" hidden /> <button className="btn" onClick={() => filePicekerRef.current.click()}>Choose</button> <button className="btn">x</button> </div> <div className="preview"> <img src="" alt="" /> <video controls src=""></video> </div> </div> );}

Now its' time to create a filePreview function.

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() { const [imagePreview, setImagePreview] = useState(null); const [videoPreview, setVideoPreview] = useState(null); const filePicekerRef = useRef(null); function previewFile(e) { // Reading New File (open file Picker Box) const reader = new FileReader(); // Gettting Selected File (user can select multiple but we are choosing only one) const selectedFile = e.target.files[0]; if (selectedFile) { reader.readAsDataURL(selectedFile); } // As the File loaded then set the stage as per the file type reader.onload = (readerEvent) => { if (selectedFile.type.includes("image")) { setImagePreview(readerEvent.target.result); } else if (selectedFile.type.includes("video")) { setVideoPreview(readerEvent.target.result); } }; }  return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input ref={filePicekerRef} accept="image/*, video/*" onChange={previewFile} type="file" hidden /> <button className="btn" onClick={() => filePicekerRef.current.click()}>Choose</button> <button className="btn">x</button> </div> <div className="preview"> <img src="" alt="" /> <video controls src=""></video> </div> </div> );}

I know it's too much so let's break it down. I am using FileReader to handle the file selection.

  • I have created an instance called reader.
  • Then we are getting the selectedFile from an input field (I am targeting only one file, the user can select multiple files but I am handling only one file).
  • If the user has selected a file then read that as Data URLs.
  • When the file is loaded then check for the file type and set the image and video accordingly.

Preview the file

After file selection is done then we need to preview the file to the user. For that I have already created a container called .preview, In that, there were two elements img and video. Now we need to render these elements conditionally. and after that they will look like this-

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() { const [imagePreview, setImagePreview] = useState(null); const [videoPreview, setVideoPreview] = useState(null); const filePicekerRef = useRef(null); function previewFile(e) { // Reading New File (open file Picker Box) const reader = new FileReader(); // Gettting Selected File (user can select multiple but we are choosing only one) const selectedFile = e.target.files[0]; if (selectedFile) { reader.readAsDataURL(selectedFile); } // As the File loaded then set the stage as per the file type reader.onload = (readerEvent) => { if (selectedFile.type.includes("image")) { setImagePreview(readerEvent.target.result); } else if (selectedFile.type.includes("video")) { setVideoPreview(readerEvent.target.result); } }; }  return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input ref={filePicekerRef} accept="image/*, video/*" onChange={previewFile} type="file" hidden /> <button className="btn" onClick={() => filePicekerRef.current.click()}>Choose</button> <button className="btn">x</button> </div> <div className="preview"> {imagePreview != null && <img src={imagePreview} alt="" />} {videoPreview != null && <video controls src={videoPreview}></video>} </div> </div> );}

Clear Input Field

Now, what if the user wants to clear the input field or remove the image he has selected. We haven't implemented that yet. To do that I've created a close button earlier. Now let's just add the functionality to it. When the user clicks on the button then it should fire clearFiles function. So let's just create it.

components/FilePreviewer.js

import { useState, useRef } from "react";export default function FilePreviewer() { const [imagePreview, setImagePreview] = useState(null); const [videoPreview, setVideoPreview] = useState(null); const filePicekerRef = useRef(null);  function previewFile(e) { // Reading New File (open file Picker Box) const reader = new FileReader(); // Gettting Selected File (user can select multiple but we are choosing only one) const selectedFile = e.target.files[0]; if (selectedFile) { reader.readAsDataURL(selectedFile); } // As the File loaded then set the stage as per the file type reader.onload = (readerEvent) => { if (selectedFile.type.includes("image")) { setImagePreview(readerEvent.target.result); } else if (selectedFile.type.includes("video")) { setVideoPreview(readerEvent.target.result); } }; } function clearFiles() { setImagePreview(null); setVideoPreview(null); } return ( <div> <h1>Preview Image/Video</h1> <div className="btn-container"> <input ref={filePicekerRef} accept="image/*, video/*" onChange={previewFile} type="file" hidden /> <button className="btn" onClick={() => filePicekerRef.current.click()}>Choose</button> <button className="btn">x</button> </div> <div className="preview"> {imagePreview != null && <img src={imagePreview} alt="" />} {videoPreview != null && <video controls src={videoPreview}></video>} </div> </div> );}

That's all we need to create a working file Previewer. It can preview an image and a video.

Now we just need to import this container in App.js and render it. App.js will look something like this.

src/App.js

import "./styles.css";import FilePreviewer from "./components/FilePreviewer"; export default function App() {return (<div className="App"><FilePreviewer /></div>);}

You can find the full code in the following Sandbox

Code Sandbox

Warning

It takes a little white to render the video if the size of the video is large. You can setup a loading state for that.

What's Next?

Now after that you can take this further and add support for other files such as text, pdf, and others. You can also add support for multiple files and there are many things you can do.

Preview File before uploading in React - Jatin Sharma (2024)

FAQs

How to show preview of image before upload in React JS? ›

To upload image and preview it using React JS we will use the HTML file input for the image input. After taking input the image url is created using URL. createObjectURL() method and store in the useState variable named file. Display the image as preview using the html img tags with the file url in the src prop.

How to show the preview of a file in React? ›

Create a components directory under the src directory. Now, create a file called ImageUpload. jsx under the src/components . This file will contain the React component to upload and preview images.

How to preview an image before uploading in JS? ›

How to Preview Images Before Upload with Javascript
  1. <input type=”file” accept=”.jpg, .jpeg, .png” id="file-upload"> <img src="#" alt="Preview Uploaded Image" id="file-preview"> As you can notice the input type has to be set to file. ...
  2. const input = document. ...
  3. const previewPhoto = () => {
Jun 16, 2021

How to upload a PDF and preview it using ReactJS? ›

To upload a PDF file in React, you can create a file input element and handle the file upload in React component using state. Then, you can send the selected file to your server or API for processing, or you can display the PDF in the browser by using a third-party library like react-pdf.

How do I Preview react code? ›

You can open the preview in either the current editor group (Markdown: Open Preview Ctrl+Shift+V) or in a new editor group to the side (Markdown: Open Preview to the Side Ctrl+K V). You'll get nice formatting, hyperlink navigation to headers, and syntax highlighting in code blocks.

How do I show a preview file? ›

Enabling Preview Pane support

Go to Options in Windows File Explorer and under the View tab, you will see a list of Advanced settings. Ensure that Show preview handlers in preview pane is selected in order for the preview pane to display.

How do you display an image file in react? ›

To display a react image that is hosted on an external server in a React component, you can use the <img> HTML tag inside a component's render method. For example: This will render a react image with the specified src URL in your React component.

How do I display a file in react? ›

Using the React File Viewer in your project is straightforward. First, you need to import the library into your project. Once you've imported the React File Viewer, you can use it to render files. You simply need to pass the file and its type as parameters to the FileViewer component.

How do I use preview image? ›

Click the View menu. It's at the top of the File Explorer window. Select an option that displays previews. Choose any of these options to display image previews in the folder: Extra large icons, Large icons, Medium icons, Tiles, or Content.

How do you upload and preview image with drag and drop in react? ›

  1. Step 0: Creating a new React. ...
  2. Step 1: Creating a new file input. ...
  3. Step 2: Using and storing the selected file from a form input. ...
  4. Step 3: Uploading a file from a form using FormData to Cloudinary. ...
  5. Step 4: Allowing only certain filetypes like images to be selected. ...
  6. Step 5: Showing a preview of an image on select.
Jul 27, 2023

How do I upload a picture to preview? ›

Connect your camera or device to your Mac, then make sure your Mac and the camera or device are turned on. If the device is locked, use a passcode or Face ID to unlock it. In the Preview app on your Mac, choose File > Import from [camera name].

How to Preview docx file in React JS? ›

Code Example for React Document Viewer

WebViewer({ ..., initialDoc: 'https://myserver.com/myfile.docx', }, document. getElementById('viewer')); You can also call loadDocument with the same parameters.

How do I embed a PDF file in React? ›

The simplest way to display a PDF document in React is by using the `<iframe>` element. You can embed the PDF file within an `<iframe>` tag and set the source to the URL of the PDF file.

How to create an image upload with preview? ›

To enable image preview before upload in web development, utilize JavaScript's FileReader class. Start by creating an HTML file input element and an image element for displaying the preview, with appropriate IDs. Then, create a JavaScript function triggered by the file input's value change.

How do you upload and preview image with drag and drop in React? ›

  1. Step 0: Creating a new React. ...
  2. Step 1: Creating a new file input. ...
  3. Step 2: Using and storing the selected file from a form input. ...
  4. Step 3: Uploading a file from a form using FormData to Cloudinary. ...
  5. Step 4: Allowing only certain filetypes like images to be selected. ...
  6. Step 5: Showing a preview of an image on select.
Jul 27, 2023

How do I check the size of an image before uploading in React? ›

By using the uploading event, you can get the file size before uploading it to the server. File object contains the file size in bytes only. You can convert the size to standard formats ( KB or MB ) using bytesToSize method. You can also explore React File Upload feature tour page for its groundbreaking features.

Top Articles
How do you choose the right storage capacity for your tablet? - Coolblue
Macrocytosis
Craigslist Vans
What are Dietary Reference Intakes?
Chalupp's Pizza Taos Menu
5 Bijwerkingen van zwemmen in een zwembad met te veel chloor - Bereik uw gezondheidsdoelen met praktische hulpmiddelen voor eten en fitness, deskundige bronnen en een betrokken gemeenschap.
Corpse Bride Soap2Day
ds. J.C. van Trigt - Lukas 23:42-43 - Preekaantekeningen
True Statement About A Crown Dependency Crossword
Florida (FL) Powerball - Winning Numbers & Results
Used Wood Cook Stoves For Sale Craigslist
Nonuclub
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Nebraska Furniture Tables
Classic Lotto Payout Calculator
Napa Autocare Locator
Grayling Purnell Net Worth
Epguides Strange New Worlds
Skip The Games Fairbanks Alaska
Craigslist Pearl Ms
Is Windbound Multiplayer
Yosemite Sam Hood Ornament
Play It Again Sports Norman Photos
Avatar: The Way Of Water Showtimes Near Maya Pittsburg Cinemas
Elite Dangerous How To Scan Nav Beacon
Craigslist Hunting Land For Lease In Ga
800-695-2780
Wonder Film Wiki
Is Henry Dicarlo Leaving Ktla
Waters Funeral Home Vandalia Obituaries
How do you get noble pursuit?
30+ useful Dutch apps for new expats in the Netherlands
Srjc.book Store
Ringcentral Background
Noaa Marine Forecast Florida By Zone
Moonrise Time Tonight Near Me
new haven free stuff - craigslist
Jr Miss Naturist Pageant
Craigslist Lakeside Az
Buhsd Studentvue
Sunrise Garden Beach Resort - Select Hurghada günstig buchen | billareisen.at
Skip The Games Grand Rapids Mi
RECAP: Resilient Football rallies to claim rollercoaster 24-21 victory over Clarion - Shippensburg University Athletics
Makes A Successful Catch Maybe Crossword Clue
CrossFit 101
Noga Funeral Home Obituaries
Keci News
Goosetown Communications Guilford Ct
Kenmore Coldspot Model 106 Light Bulb Replacement
Noelleleyva Leaks
Vrca File Converter
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 6161

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.