Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active February 4, 2020 12:03
Show Gist options
  • Save VitorLuizC/14ca2d4f5a0809de23667a19e4949efb to your computer and use it in GitHub Desktop.
Save VitorLuizC/14ca2d4f5a0809de23667a19e4949efb to your computer and use it in GitHub Desktop.
A React Hook that prevents browser to open file when drop it.
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