Image Previews in React: A Step-by-Step Guide

Image Previews in React: A Step-by-Step Guide

Browsing Image Files in React

To add file upload functionality to your web application, you can use an input element of type “file”. This allows users to select single or multiple files from their device.

<input type="file" accept="image/*" />

Introduction to the FileReader API

The FileReader API provides an interface for asynchronously reading the contents of a file. We’ll use this API to read the selected image files and preview them.

Previewing Single Images

To preview a single image, we’ll create a React component that uses the FileReader API to read the selected file.


import React, { useState, useEffect } from 'eact';

const SingleImagePreview = () => {
  const [image, setImage] = useState(null);
  const [preview, setPreview] = useState(null);

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    setImage(file);
  };

  useEffect(() => {
    if (image) {
      const reader = new FileReader();
      reader.onload = (event) => {
        setPreview(event.target.result);
      };
      reader.readAsDataURL(image);
    }
  }, [image]);

  return (
    <div>
      {preview && <img src={preview} alt="Image Preview" />}
    </div>
  );
};

Previewing Multiple Images

To preview multiple images, we’ll modify the previous code to handle multiple files.


import React, { useState, useEffect } from 'eact';

const MultipleImagePreview = () => {
  const [images, setImages] = useState([]);
  const [previews, setPreviews] = useState([]);

  const handleFileChange = (event) => {
    const files = event.target.files;
    setImages(files);
  };

  useEffect(() => {
    if (images.length > 0) {
      const readers = [];
      images.forEach((image) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          setPreviews((prevPreviews) => [...prevPreviews, event.target.result]);
        };
        reader.readAsDataURL(image);
        readers.push(reader);
      });
      return () => {
        readers.forEach((reader) => reader.abort());
      };
    }
  }, [images]);

  return (
    <div>
      {previews.map((preview, index) => (
        <img key={index} src={preview} alt={`Image Preview ${index + 1}`} />
      ))}
    </div>
  );
};

By Alex Rivers

I write hands-on guides to web development and programming: JavaScript and React patterns, Python scripting, CSS layout and the developer tools that tie it all together. I like explanations that start with working code and end with knowing why it works. If a post saves you an afternoon of debugging, it did its job.