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';45interface Props {6 name: string;7}89interface InputRefProps extends HTMLInputElement {10 acceptedFiles: File[];11}1213export default function ReactDropzoneInput({ name }: Props) {14 const inputRef = useRef<InputRefProps>(null);15 const { fieldName, registerField, defaultValue = [] } = useField(name);1617 const [acceptedFiles, setAcceptedFiles] = useState<File[]>(defaultValue);1819 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 });2829 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]);4647 return (48 <div {...getRootProps()} onClick={() => inputRef.current?.click()}>49 <input {...getInputProps()} accept="image/*" ref={inputRef} />5051 {acceptedFiles.length !== 0 && (52 <ul>53 {acceptedFiles.map(file => (54 <li key={file.name}>{file.name}</li>55 ))}56 </ul>57 )}5859 {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};