Published on

React Tips: Upload Image in Next.js or React App

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

Reusable Hook: useUploadLocalImage

// src/features/documents/hooks/use-upload-local-image.ts
import { useEditorStore } from "@/features/documents/store/use-editor-store";

export const useUploadLocalImage = () => {
  const { editor } = useEditorStore();

  const onChange = (src: string) => {
    editor?.chain().focus().setImage({ src }).run();
  };

  const onUploadLocalImage = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const url = URL.createObjectURL(file);
        onChange(url);
      }
    };
    input.click();
  };

  return { onUploadLocalImage };
};

Usage

import { useUploadLocalImage } from "@/features/documents/hooks/use-upload-local-image";
import { UploadIcon } from "@/components/icons";

const MyComponent = () => {
  const { onUploadLocalImage } = useUploadLocalImage();

  return (
    <DropdownMenu>
      <DropdownMenuItem onClick={onUploadLocalImage}>
        <UploadIcon className="size-4" />
        Upload
      </DropdownMenuItem>
    </DropdownMenu>
  );
};