Skip to content

useFileDropArea

Build a file drop area component easily with this hook, it handles file dropping to a label of a file input.

Options

NameTypeDescription
refRefObjectthe target element reference.
multipleBooleanuse multiple files or not (default is false).
onUploadFunctiona handler that will be executed when the user uploads any files, and it takes an array of Files.

Return Values

a ref object of the target element.

DroppedFile Object

NameTypeDescription
nameStringthe filename.
sizeNumberthe file size in MB.
extensionStringthe file extension.
dataFileDatathe file data type depends on readAs option, if you don't use this it will be a File object.

INFO

You can add <input type="file" /> inside the area element and the input files will also be included.

Example Usage

tsx
import { useArray, useFileDropArea } from 'react-pre-hooks';

export default function Example() {
  const images = useArray<string>([]);

  const ref = useFileDropArea({
    multiple: true,
    onUpload: files =>
      files.forEach(file => {
        const reader = new FileReader();
        reader.onload = () => images.push(reader.result as string);
        reader.readAsDataURL(file);
      })
  });

  return (
    <main>
      <h1>Drop images to this box!</h1>
      <label ref={ref}>
        {images.values.map((image, index) => (
          <img key={index} alt={`image-${index}`} src={image} />
        ))}
        <input type="file" accept="image/*" hidden />
      </label>
    </main>
  );
}
import { useArray, useFileDropArea } from 'react-pre-hooks';

export default function Example() {
  const images = useArray<string>([]);

  const ref = useFileDropArea({
    multiple: true,
    onUpload: files =>
      files.forEach(file => {
        const reader = new FileReader();
        reader.onload = () => images.push(reader.result as string);
        reader.readAsDataURL(file);
      })
  });

  return (
    <main>
      <h1>Drop images to this box!</h1>
      <label ref={ref}>
        {images.values.map((image, index) => (
          <img key={index} alt={`image-${index}`} src={image} />
        ))}
        <input type="file" accept="image/*" hidden />
      </label>
    </main>
  );
}

Released under the MIT License.