Preview an Image Before it is Uploaded - React.js

Ever wanted to show your users a sneak peek of their image before they upload it?

It's easier than you think! Let's create a simple React component to do just that.

It's easy with URL.createObjectURL(). Here's how:

import React, { useState, useEffect } from "react";

function ImageUploader() {
  const [image, setImage] = useState(null);
  const [preview, setPreview] = useState(null);

  useEffect(() => {
    // Clean up the URL when the component unmounts or the image changes
    return () => {
      if (preview) URL.revokeObjectURL(preview);
    };
  }, [preview]);

  const handleImageChange = (e) => {
    // Grab the file we need
    const file = e.target.files[0];
    if (file) {
      setImage(file);
      // Create a preview URL for the new image
      const newPreview = URL.createObjectURL(file);
      // Clean up old preview URL if it exists
      if (preview) URL.revokeObjectURL(preview);
      setPreview(newPreview);
    }
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleImageChange} />
      {preview && <img src={preview} alt="Preview" style={{maxWidth: '200px'}} />}
      {image && <button>Upload Image</button>}
    </div>
  );
}

export default ImageUploader;

If you don't just blindly copy and paste, let's break it down so you understand why it works:

  1. We're using two state variables: image for the file and preview for the preview URL.

  2. The magic happens in handleImageChange:

    • When selecting a file, we create a preview URL with URL.createObjectURL(file).
    • This URL lets us display the image instantly; no server upload is needed!
  3. We're using useEffect to clean up:

    • Whenever preview changes or the component unmounts, we call URL.revokeObjectURL(preview).
    • It frees up memory when we're done with the preview.
  4. In the JSX:

    • We show the preview image if we have a preview URL.
    • We display an upload button when an image is selected (though we're not handling the upload here).

And that's it! With this simple component, your users can see their image before uploading it. A slight touch that makes your app feel more responsive and user-friendly.

URL.createObjectURL() is excellent for quick previews, but you might want to look into alternative solutions for handling lots of images or in long-running apps.

Reactjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.