Unform

React Dropzone

React Dropzone

React Dropzone is a simple React hook to create a HTML5-compliant drag'n'drop zone for files.

⚠️ All examples below are using TypeScript. If you're not using it, you can remove all type definitions from the component definition.

Click here to access a React Dropzone Input Live Demo.

React Dropzone input component

1import React, { useEffect, useRef, useState } from 'react';
2import { useDropzone } from 'react-dropzone';
3import { useField } from '@unform/core';
4
5interface Props {
6 name: string;
7}
8
9interface InputRefProps extends HTMLInputElement {
10 acceptedFiles: File[];
11}
12
13export default function ReactDropzoneInput({ name }: Props) {
14 const inputRef = useRef<InputRefProps>(null);
15 const { fieldName, registerField, defaultValue = [] } = useField(name);
16
17 const [acceptedFiles, setAcceptedFiles] = useState<File[]>(defaultValue);
18
19 const { getRootProps, getInputProps, isDragActive } = useDropzone({
20 accept: 'image/*',
21 onDrop: onDropAcceptedFiles => {
22 if (inputRef.current) {
23 inputRef.current.acceptedFiles = onDropAcceptedFiles;
24 setAcceptedFiles(onDropAcceptedFiles);
25 }
26 },
27 });
28
29 useEffect(() => {
30 registerField({
31 name: fieldName,
32 ref: inputRef.current,
33 getValue: (ref: InputRefProps) => {
34 return ref.acceptedFiles || [];
35 },
36 clearValue: (ref: InputRefProps) => {
37 ref.acceptedFiles = [];
38 setAcceptedFiles([]);
39 },
40 setValue: (ref: InputRefProps, value) => {
41 ref.acceptedFiles = value;
42 setAcceptedFiles(value);
43 },
44 });
45 }, [fieldName, registerField]);
46
47 return (
48 <div {...getRootProps()} onClick={() => inputRef.current?.click()}>
49 <input {...getInputProps()} accept="image/*" ref={inputRef} />
50
51 {acceptedFiles.length !== 0 && (
52 <ul>
53 {acceptedFiles.map(file => (
54 <li key={file.name}>{file.name}</li>
55 ))}
56 </ul>
57 )}
58
59 {isDragActive ? (
60 <p>Drop the files here ...</p>
61 ) : (
62 <p>Drag drop some files here, or click to select files</p>
63 )}
64 </div>
65 );
66};
Edit this page on GitHub