Clue Mediator

Handle drag over and out in React

📅August 11, 2021

In this article, we will show you how to handle drag over and out in React for the file upload.

Here, we will see the drag over and out functionality with an example. You may use this functionality along with the file upload feature.

Checkout more articles on ReactJS

Demo Application

Output - Handle drag over and out in React - Clue Mediator

Output - Handle drag over and out in React - Clue Mediator

Steps to implement drag over and out in React

  1. Create a simple react app
  2. Write logic to handle drag over and out
  3. Output

1. Create a simple react app

Let’s create a simple react application using the `create-react-app` npm package. Run the following command to create an app.

npx create-react-app drag-over-out-react-app

2. Write logic to handle drag over and out

Now, we will use two different sections (Container and Drag & Drop Area) to handle the drag over and drag out functionality.

We will attach the `onDragEnter` event to the first section (Container) so we can show the second section on drag over action. Similarly we have to attach the `onDragLeave` event to the second section (Drag & Drop Area) so we can handle the drag out action.

App.js

import React, { useState } from 'react';

function App() {
  const [dnd, setDnd] = useState(false);

  const handleDragEnter = event => {
    console.log('On Drag Enter >>> ', event.target.className);
    setDnd(!dnd);
  };

  const handleDragLeave = event => {
    console.log('On Drag Leave >>> ', event.target.className);
    setDnd(!dnd);
  };

  return (
    <div>
      <h3>Handle drag over and out in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h3>
      <div class="box-container">
        <div class="box" ondragenter={handleDragEnter}>
          Container
        </div>
        {dnd && <div class="drop-box" ondragleave={handleDragLeave}>Drag & Drop Area</div>}
      </div>
    </div>
  );
}

export default App;

Let’s use the following CSS to design the component.

index.css

body {
  margin: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.box-container {
  position: relative;
  margin-top: 10px;
}
.box {
  border: 1px solid #999;
  height: 200px;
  padding: 20px;
  border-radius: 5px;
}
.drop-box {
  background-color: #e2e6a1;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  border: 1px solid #999;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}

Output

Run the react app and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project