DEV Community

Cover image for How to Handle Pasted Images in React Without Losing Your Mind
Gouranga Das Samrat
Gouranga Das Samrat

Posted on

How to Handle Pasted Images in React Without Losing Your Mind

How to Handle Pasted Images in React Without Losing Your Mind

Recently I was working on a freature that required pasting images into the React app input. That’s when I got to know browsers handle clipboard data inconsistently.

I started playing around with the Clipboard API, trying to make image pasting smooth and reliable. You know the struggle: users expect to Ctrl+V an image and see it appear instantly, like magic. I needed a reliable way to capture and display those images without breaking the user experience.

What’s Going On When You Paste?

When you hit Ctrl+V, the browser fires a ClipboardEvent.

This event carries a clipboardData object, packed with whatever the user copied: text, images, or even files.

The clipboardData object is your key. It’s got:

types: Lists what’s in the clipboard (like “image/png”).

files: Holds actual file objects, including images.

getData(): Grabs raw data for specific MIME types.

How It All Fits Together

Each paste event gives you a chance to grab the image. The clipboardData.files array is where images live. It’s a FileList, with each item having:

type: The MIME type, like “image/jpeg”.

kind: It will be either “string” or “file”.

A Clean Solution to Handle Pasted Images

Here’s a reusable component I built to catch pasted images and display them:

import React, { useState, useEffect, useRef } from "react";
const ImagePasteInput = () => {
  const [pastedFiles, setPastedFiles] = useState([]);
  const [inputValue, setInputValue] = useState("");
  const inputRef = useRef(null);
  const containerRef = useRef(null);
  // Set up paste event listener on the document
  useEffect(() => {
    const handlePaste = (event) => {
      // Check if our input element is focused
      if (document.activeElement !== inputRef.current) return;
      const items = event.clipboardData?.items;
      if (!items) return;
      // Process image files
      const newFiles = [];
      Array.from(items).forEach((item) => {
        if (item.kind === "file" && item.type.startsWith("image/")) {
          const file = item.getAsFile();
          if (file) {
            newFiles.push({
              url: URL.createObjectURL(file),
              name: file.name || `pasted-image-${Date.now()}.png`,
              type: file.type,
              size: file.size,
              file: file,
            });
          }
        }
      });
      if (newFiles.length > 0) {
        setPastedFiles((prev) => [...prev, ...newFiles]);
        event.preventDefault(); // Prevent pasting text into input
      }
    };
    document.addEventListener("paste", handlePaste);
    return () => {
      document.removeEventListener("paste", handlePaste);
    };
  }, []);
  // Clean up object URLs on unmount
  useEffect(() => {
    return () => {
      pastedFiles.forEach((file) => URL.revokeObjectURL(file.url));
    };
  }, [pastedFiles]);
  const handleRemoveFile = (index) => {
    setPastedFiles((prev) => {
      const newFiles = [...prev];
      URL.revokeObjectURL(newFiles[index].url);
      newFiles.splice(index, 1);
      return newFiles;
    });
  };
  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };
  const handleUpload = () => {
    // Example function to handle the upload of pasted files
    console.log(
      "Files to upload:",
      pastedFiles.map((file) => file.file)
    );
    // Here you would typically send these files to your server
  };
  return (
    <div
      style={{
        margin: "30px",
        padding: "10px",
        border: "2px solid black",
        borderRadius: "8px",
      }}
      ref={containerRef}
    >
      <div style={{ marginBottom: "20px" }}>
        <label htmlFor="pasteInput">
          Paste images here (click and press Ctrl+V):
        </label>
        <input
          ref={inputRef}
          id="pasteInput"
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          placeholder="Click here and paste images with Ctrl+V"
          style={{
            display: "block",
            width: "90%",
            padding: "8px",
            border: "1px solid #ccc",
            borderRadius: "4px",
            marginTop: "5px",
          }}
        />
      </div>
      {pastedFiles.length > 0 && (
        <div>
          <h3>Pasted Images:</h3>
          <div style={{ display: "flex", flexWrap: "wrap", gap: "10px" }}>
            {pastedFiles.map((file, index) => (
              <div
                key={index}
                style={{
                  border: "1px solid #eee",
                  padding: "10px",
                  borderRadius: "4px",
                }}
              >
                <img
                  src={file.url}
                  alt={file.name}
                  style={{ maxWidth: "200px", maxHeight: "200px" }}
                />
                <div>Type: {file.type}</div>
                <div>Size: {Math.round(file.size / 1024)} KB</div>
                <button
                  onClick={() => handleRemoveFile(index)}
                  style={{ marginTop: "5px", padding: "4px 8px" }}
                >
                  Remove
                </button>
              </div>
            ))}
          </div>
          <button
            onClick={handleUpload}
            style={{
              marginTop: "20px",
              padding: "8px 16px",
              backgroundColor: "#4285f4",
              color: "white",
              border: "none",
              borderRadius: "4px",
              cursor: "pointer",
            }}
          >
            Upload Images
          </button>
        </div>
      )}
    </div>
  );
};

const App = () => (
  <div>
    <ImagePasteInput />
  </div>
);

export default App;
Enter fullscreen mode Exit fullscreen mode

This is a very simple example of a React input component which allows you to paste images directly in the React application and upload them.

Few Things To Remember

Clipboard data can be of several types including but not limited to plain text, rich text, images, files from explorer/finder, mixed content of different types.

When an image from clipboard is pasted then it will be available like a file object in clipboard. The images from clipboard will have a MIME type like: image/png.

The trick to display image pasted from the clipboard is to create an object URL.

Final Takeaway

Today we explored some simple techniques with JavaScript Clipboard API. Try it in your next project and share your thoughts in the clipboard.

Let’s meet again in another JavaScript adventure.

Thank you for being a part of the community

Top comments (0)