Created
February 14, 2022 06:23
-
-
Save tw4204/c9fbac9fab576170bfd0c4d9c1692597 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useCallback } from 'react' | |
export const useDragAndDrop = ({ onChange, dragRef }) => { | |
const [isDragging, setIsDragging] = useState(false) | |
const handleDragIn = useCallback((e) => { | |
e.preventDefault() | |
e.stopPropagation() | |
}, []) | |
const handleDragOut = useCallback((e) => { | |
e.preventDefault() | |
e.stopPropagation() | |
setIsDragging(false) | |
}, []) | |
const handleDragOver = useCallback((e) => { | |
e.preventDefault() | |
e.stopPropagation() | |
if (e.dataTransfer.files) { | |
setIsDragging(true) | |
} | |
}, []) | |
const handleDrop = useCallback((e) => { | |
e.preventDefault() | |
e.stopPropagation() | |
onChange(e) | |
setIsDragging(false) | |
}, [onChange]) | |
const initDragEvents = useCallback(() => { | |
if (dragRef.current !== null) { | |
dragRef.current.addEventListener('dragenter', handleDragIn) | |
dragRef.current.addEventListener('dragleave', handleDragOut) | |
dragRef.current.addEventListener('dragover', handleDragOver) | |
dragRef.current.addEventListener('drop', handleDrop) | |
} | |
}, [handleDragIn, handleDragOut, handleDragOver, handleDrop]) | |
const resetDragEvents = useCallback(() => { | |
if (dragRef.current !== null) { | |
dragRef.current.removeEventListener('dragenter', handleDragIn) | |
dragRef.current.removeEventListener('dragleave', handleDragOut) | |
dragRef.current.removeEventListener('dragover', handleDragOver) | |
dragRef.current.removeEventListener('drop', handleDrop) | |
} | |
}, [handleDragIn, handleDragOut, handleDragOver, handleDrop]) | |
useEffect(() => { | |
initDragEvents() | |
return () => resetDragEvents() | |
}, [initDragEvents, resetDragEvents]) | |
return isDragging | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reference:
https://velog.io/@yiyb0603/React%EC%97%90%EC%84%9C-%EB%93%9C%EB%9E%98%EA%B7%B8-%EC%95%A4-%EB%93%9C%EB%A1%AD%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-%ED%8C%8C%EC%9D%BC-%EC%97%85%EB%A1%9C%EB%93%9C-%ED%95%98%EA%B8%B0