Enable Dark Mode!
how-to-create-an-image-preview-component-in-react.jpg
By: Alan Joy

How to Create an Image Preview Component in React

Technical odoo React

When we are building a form with image upload options, including an option to preview the uploaded image can really improve the user experience. With this feature, users can view the uploaded image and also change the image if they uploaded the wrong image. With React, we can set up this feature easily with the help of file inputs, useState, and browser URL methods. In this blog, we will create a simple image upload and image preview component step by step using React and its methods.

1. Create a React Project

First, we can create a React project using Vite. Run the following commands for a new Vite project.

npm create vite@latest react-image-preview -- --template react
cd react-image-preview
npm install
npm run dev

2. How image preview works

Before we start writing our components, let's look at how the image preview works in the React app. When a user selects an image in the file input field, we will save that image in a React state and then create a temporary URL for that image using the createObjectURL method. Now, we can assign this URL as the image src attribute to an image element. This way, we can display the selected image without needing to upload it to a server first and display it in the local session of the browser itself.

const imageUrl = URL.createObjectURL(file);

3. Create the Image Preview Component

Now, we can start developing our image preview component. First, create a component named ImagePreview.jsx. We need to add two state values for our app. One to store the selected image and the other to store the preview url created. Add this code to the component.

import { useState } from "react";
export default function ImagePreview() {
 const [image, setImage] = useState(null);
 const [preview, setPreview] = useState("");
 return (
   <div>
     <input type="file" accept="image/*" />
   </div>
 );
}

4. Handle Image Selection

Next, we need to detect when a user selects an image and then create an image preview url for that image. We can add this function to our app using the onChange event of the file input. Update the component and add this function to it.

const handleImageChange = (event) => {
 const file = event.target.files[0];
 if (file) {
   setImage(file);
   setPreview(URL.createObjectURL(file));
 }
};

Add onChange to the file input to connect the function

<input
 type="file"
 accept="image/*"
 onChange={handleImageChange}
/>

5. Display the Selected Image

Now, we have created the preview URL; next, we need to display that preview. We can use an image element to display the image preview. Add this code to our component.

{preview && (
 <div>
   <img
     src={preview}
     alt="Selected preview"
     width="200"
   />
 </div>
)}

6. Add Basic Image Validation

Next, we can set up a basic validation for our form. A file input can allow users to select any format of files, so it is a good practice to add validation to check if the user uploads the correct files to our input. Update the component with this code.

const handleImageChange = (event) => {
 const file = event.target.files[0];
 if (!file) return;
 if (!file.type.startsWith("image/")) {
   alert("Please select a valid image.");
   return;
 }
 if (file.size > 5 * 1024 * 1024) {
   alert("Image size must be less than 5 MB.");
   return;
 }
 setImage(file);
 setPreview(URL.createObjectURL(file));
};

7. Add a Remove Image Option

Now, we can add a remove button to remove the selected image. It is a good idea to add this option because users can sometimes select the wrong image, so they need an option to change the selected image. Add this function to our component.

const removeImage = () => {
 if (preview) {
   URL.revokeObjectURL(preview);
 }
 setImage(null);
 setPreview("");
};

Now, add a button to remove it in the component.

{preview && (
 <div>
   <img src={preview} alt="Selected preview" />
   <button onClick={removeImage}>
     Remove Image
   </button>
 </div>
)}

8. Complete Image Preview Component

export default function ImagePreview() {
 const [image, setImage] = useState(null);
 const [preview, setPreview] = useState("");
 useEffect(() => {
   if (!image) {
     setPreview("");
     return;
   }
   const objectUrl = URL.createObjectURL(image);
   setPreview(objectUrl);
   return () => {
     URL.revokeObjectURL(objectUrl);
   };
 }, [image]);
 const handleImageChange = (event) => {
   const file = event.target.files[0];
   if (!file) return;
   if (!file.type.startsWith("image/")) {
     alert("Please select a valid image.");
     event.target.value = "";
     return;
   }
   if (file.size > 5 * 1024 * 1024) {
     alert("Image size must be less than 5 MB.");
     event.target.value = "";
     return;
   }
   setImage(file);
 };
 const removeImage = () => {
   setImage(null);
 };
 return (
   <div className="mx-auto max-w-md rounded-lg border p-6">
     <h2 className="mb-4 text-lg font-semibold">
       Upload an Image
     </h2>
     <input
       type="file"
       accept="image/*"
       onChange={handleImageChange}
       className="mb-4 w-full"
     />
     {preview && (
       <div className="space-y-4">
         <img
           src={preview}
           alt="Selected preview"
           className="h-60 w-full rounded-lg object-contain"
         />
         <button
           onClick={removeImage}
           className="rounded bg-red-500 px-4 py-2 text-white"
         >
           Remove Image
         </button>
       </div>
     )}
   </div>
 );
}

Now, import this component into our App.jsx file to use it

import ImagePreview from "./ImagePreview";
function App() {
 return (
   <div className="p-6">
     <ImagePreview />
   </div>
 );
}
export default App;

9. Upload the Image to a Backend

Now, we have developed the image preview feature. For a real-life form, we need to upload the image to a backend. We can also create a sample form submit function that handles the upload to the server.

const handleUpload = async () => {
 if (!image) return;
 const formData = new FormData();
 formData.append("image", image);
 const response = await fetch("/api/upload", {
   method: "POST",
   body: formData,
 });
 if (response.ok) {
   alert("Image uploaded successfully!");
 }
};

In this blog, we have checked how to create an image preview for a form. We have also checked the React state, file inputs, and the createObjectURL method; with the help of these, we developed a simple image preview. We can also add extra features to our image upload and preview, like a drag-and-drop feature, multiple image previews, image cropping, etc.

To read more about How to Build a PDF Upload and Preview Feature in React, refer to our blog, How to Build a PDF Upload and Preview Feature in React.


Frequently Asked Questions

How do I preview an image before uploading it in React?

Use URL.createObjectURL() to generate a temporary URL from the selected file. Set that URL as the src of an image element.

Do I need a backend to preview an image in React?

No. React can preview locally selected images directly in the browser without uploading them to a server.

Why should I use URL.revokeObjectURL()?

It releases the resources associated with a temporary object URL. This helps prevent unnecessary memory usage when images are replaced or the component is unmounted.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



WhatsApp