Last active
February 4, 2020 12:03
-
-
Save VitorLuizC/14ca2d4f5a0809de23667a19e4949efb to your computer and use it in GitHub Desktop.
A React Hook that prevents browser to open file when drop it.
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 { useEffect, useCallback } from 'react'; | |
/** | |
* React Hook that prevents the browser from opening files when a user drops | |
* files on the screen. It doesn't affect component specific drag-and-drop | |
* behavior since it prevents the default behavior of bubbled events on the | |
* higher instance (Window). | |
*/ | |
const useDontOpenFileOnDrop = () => { | |
const handleDrop = useCallback((event: DragEvent) => { | |
event.preventDefault(); | |
event.stopPropagation(); | |
}, []); | |
const handleDragOver = useCallback((event: DragEvent) => { | |
event.preventDefault(); | |
event.stopPropagation(); | |
}, []); | |
useEffect(() => { | |
window.addEventListener('dragover', handleDragOver); | |
window.addEventListener('drop', handleDrop); | |
return () => { | |
window.removeEventListener('dragover', handleDragOver); | |
window.removeEventListener('drop', handleDrop); | |
}; | |
}, [handleDragOver, handleDrop]); | |
}; | |
export default useDontOpenFileOnDrop; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment