Fix For React onDragExit and onDrop Events Not Working In Chrome

Viewed 2705

I have created a div to enable me to drag and drop files. When you drag file over the div, the onDragEnter React event fires with no problem.

However onDragExit event does not fire when you drag out of div. Also onDrop event does not fire when you drop the file therefore the browser opens the file even if you add the e.preventDefault() in the onDrop handler.

I have searched over the internet for fixes and non seems to work. Others claim is a bug in Chrome e.t.c.

The code below is the code in index.js. You can also check the full sample project code and edit it on Stackblitz at https://stackblitz.com/edit/react-fnkaqk?file=index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

const App = () => {

  const handleOnDragEnter = (event) => {

    console.log("draged enter");
  };

  const handleOnDragExit = (event) => {

    console.log("drag exit");
  };

  const handleOnDrop = (event) => {
    event.preventDefault();

    console.log("droped");
  };

  return (
    <>
    <h1>Drag File And Drop</h1>

    <div style={{height: "100px", backgroundColor: "purple"}} onDrop={handleOnDrop} onDragEnter={handleOnDragEnter} onDragExit={handleOnDragExit}></div>
  </>
  )
}
render(<App />, document.getElementById('root'));
1 Answers

This is weird problem with different browsers, one thing you should change is change OnDragExit to OnDragLeave

as the definition given in docs

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

With the other thing to stop drop to download file, what I have done in past is to prevent default on both onDrop and onDragOver

<div
    id="source"
    style={{ height: "100px", backgroundColor: "purple" }}
    onDragOver={handleOnDrop}
    onDrop={handleOnDrop}
    onDragEnter={handleOnDragEnter}
    onDragLeave={handleOnDragExit}
  ></div>
Related