Handle drag over and out in React
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
Steps to implement drag over and out in React
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.
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 className="box-container"> <div className="box" onDragEnter={handleDragEnter}> Container </div> {dnd && <div className="drop-box" onDragLeave={handleDragLeave}>Drag & Drop Area</div>} </div> </div> ); } export default App; |
Let’s use the following CSS to design the component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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..!! 🙂