2/28/2023 5:03:09 PM

The following code performs a simple drag and drop in a React Component Class. It allows you to drag and image and drop it into a div. It uses onDragStart, onDragEnter, onDragLeave, onDragOver, and onDrop.

import React, { Component } from 'react'; export default class DragAndDrop extends Component { constructor(props) { super(props); this.state = { selected_image_url: "", } this.drag_obj = null; } onDragStart = (e, obj) => { console.log("onDragStart"); this.drag_obj = obj; } onDragEnter = (e) => { console.log("onDragEnter"); } onDragLeave = (e) => { console.log("onDragLeave"); } onDragOver = (e) => { //this seems to do nothing but is needed for the code to work //React bug? e.preventDefault(); } onDragDrop = (e) => { console.log("onDragDrop"); //check if the drop is on the intended destination if (e.target.className === "destination") { this.setState({ selected_image_url: this.drag_obj }); } this.drag_obj = null; } render() { let image_urls = [ "https://nleomf.org/wp-content/uploads/2022/03/ny-yankees-event-icon.png", "https://s3.amazonaws.com/images.hamlethub.com/hh20mediafolder/4752/202009/mets-1600184596.jpg", "https://live.staticflickr.com/3310/3256231883_3d1276217c_b.jpg", "https://www.fantasyguru.com/wp-content/uploads/2019/07/ny-jets.jpg", ]; let bg_image_url = "url(" + this.state.selected_image_url + ")"; return ( <div style={{ display: "flex" }}> <div className="sources" style={{ margin: 20 }}> {image_urls.map(image_url => { return ( <img key={image_url} className="source" draggable="true" src={image_url} style={{ width: 100, height: 100, display: "block", marginBottom: 10 }} onDragStart={(e) => this.onDragStart(e, image_url)} /> ); })} </div> <div className="destination" style={{ backgroundColor: "blue", backgroundImage: bg_image_url, width: 400, height: 400, margin: 20, backgroundSize: "cover", backgroundRepeat: "no-repeat", backgroundPosition: "center", }} onDragEnter={this.onDragEnter} onDragLeave={this.onDragLeave} onDragOver={this.onDragOver} onDrop={this.onDragDrop} > </div> </div > ) } }