aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/components/ui/file-picker-button.tsx
blob: 95e7bbcd334efc819b2135eeb6aa1d72fdf12cbd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import React, { ChangeEvent, useRef } from "react";

import { ActionButton, ActionButtonProps } from "./action-button";

interface FilePickerButtonProps extends Omit<ActionButtonProps, "onClick"> {
  onFileSelect?: (file: File) => void;
  accept?: string;
  multiple?: boolean;
}

const FilePickerButton: React.FC<FilePickerButtonProps> = ({
  onFileSelect,
  accept,
  multiple = false,
  ...buttonProps
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      if (onFileSelect) {
        if (multiple) {
          Array.from(files).forEach(onFileSelect);
        } else {
          onFileSelect(files[0]);
        }
      }
    }
  };

  return (
    <div>
      <ActionButton onClick={handleButtonClick} {...buttonProps} />
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        className="hidden"
        accept={accept}
        multiple={multiple}
      />
    </div>
  );
};

export default FilePickerButton;