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:
We're using two state variables:
image
for the file andpreview
for the preview URL.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!
- When selecting a file, we create a preview URL with
We're using
useEffect
to clean up:- Whenever
preview
changes or the component unmounts, we callURL.revokeObjectURL(preview)
. - It frees up memory when we're done with the preview.
- Whenever
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).
- We show the preview image if we have a
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.