hooks.tsx 991 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { useCallback, useState } from 'react'
  2. export const useDraggableUploader = <T extends HTMLElement>(setImageFn: (file: File) => void) => {
  3. const [isDragActive, setIsDragActive] = useState(false)
  4. const handleDragEnter = useCallback((e: React.DragEvent<T>) => {
  5. e.preventDefault()
  6. e.stopPropagation()
  7. setIsDragActive(true)
  8. }, [])
  9. const handleDragOver = useCallback((e: React.DragEvent<T>) => {
  10. e.preventDefault()
  11. e.stopPropagation()
  12. }, [])
  13. const handleDragLeave = useCallback((e: React.DragEvent<T>) => {
  14. e.preventDefault()
  15. e.stopPropagation()
  16. setIsDragActive(false)
  17. }, [])
  18. const handleDrop = useCallback((e: React.DragEvent<T>) => {
  19. e.preventDefault()
  20. e.stopPropagation()
  21. setIsDragActive(false)
  22. const file = e.dataTransfer.files[0]
  23. if (!file)
  24. return
  25. setImageFn(file)
  26. }, [setImageFn])
  27. return {
  28. handleDragEnter,
  29. handleDragOver,
  30. handleDragLeave,
  31. handleDrop,
  32. isDragActive,
  33. }
  34. }