React Drag and Drop: Div Resisting Dragging

I recently attempted to create a drag and drop list feature in a React app without using any external packages. I came across a tutorial that claimed to achieve this.

This is the code I implemented:

class App extends React.Component {
  state = {
    items: ["3", "2", "1", "4"]
  };

  onDragStart = (e, index) => {
    console.log("drag start!!!");
    this.draggedItem = this.state.items[index];
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/html", e.target.parentNode);
    e.dataTransfer.setDragImage(e.target.parentNode, 20, 20);
  };

  onDragOver = index => {
    const draggedOverItem = this.state.items[index];

    if (this.draggedItem === draggedOverItem) {
      return;
    }

    let items = this.state.items.filter(item => item !== this.draggedItem);

    items.splice(index, 0, this.draggedItem);

    this.setState({ items });
  };

  onDragEnd = () => {
    this.draggedIdx = null;
  };

  render() {
    return (
      <div className="App">
        <main>
          <h3>List of items</h3>
          <ul>
            {this.state.items.map((item, idx) => (
              <li key={item} onDragOver={() => this.onDragOver(idx)}>
                <div
                  className="drag"
                  draggable
                  onDragStart={e => this.onDragStart(e, idx)}
                  onDragEnd={this.onDragEnd}
                  style={{ cursor: "pointer" }}
                />
                <span className="content" style={{ cursor: "pointer" }}>
                  {item}
                </span>
              </li>
            ))}
          </ul>
        </main>
      </div>
    );
  }
}

Despite no errors showing up in the console, the drag functionality in the list doesn't work as intended. Occasionally, an item can be dragged but placing it where intended creates unexpected gaps or spaces: https://i.sstatic.net/VN4bn.png

The codesandbox with this implementation can be found here:https://codesandbox.io/s/angry-dewdney-xzhsi

Answer №1

To improve user experience, consider updating the render method to enclose the draggable div around the text span as shown below:

<div
 className="drag"
 draggable
 onDragStart={e => this.onDragStart(e, idx)}
 onDragEnd={this.onDragEnd}
 style={{ cursor: "pointer" }}
>
   <span className="content" style={{ cursor: "pointer" }}>
      {item}
   </span>
</div>

This adjustment ensures that clicking on the text also triggers the draggable functionality, rather than having to click on an empty div nearby.

Answer №2

To make an element draggable, simply add the attribute "draggable=true". Ensure that the element you want to drop onto has the necessary code to allow dropping, as HTML does not automatically enable this feature.

    Add the following code to enable dropping: onDragOver={event=>event.preventDefault()}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which one is better: JSON in PHP or JSON in Javascript?

In my current project, I am working on a website that utilizes a PHP function to retrieve JSON data and present it on the webpage. However, I have noticed that when the page loads, it freezes until the response is successfully fetched, creating a visual di ...

Unable to see Primereact styles reflected on components

After some investigation, I've pinpointed the issue to be related to preflight from tailwind. Upon reviewing the documentation, I came across this helpful information: CSS Layer It seems that using Tailwind CSS with styled or unstyled modes of PrimeR ...

Issue with Loading JQuery AutoComplete

Issue with Code Javascript Code using Jquery: $('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) { location.href = item.AGE; }); Json Data: ...

Designing a Dynamic Page Layout with Flexbox or Grid

I have been attempting to create this specific layout using a grid system. Unfortunately, I have not been successful in achieving the desired result with my current code snippet. Please note: The DOM Structure cannot be altered https://i.stack.imgur.com/b ...

Utilizing Vue JS for applying multiple filters on a single array

I'm currently facing challenges in optimizing my code. I've successfully created dynamically generated objects from an array, implemented a search function, and had a working filter (just one) at some point. However, my attempt to chain the filte ...

Tips for integrating Tailwind CSS into Create React App using React

I recently started using tailwindcss with my react app. I tried to follow the guide from tailwindcss but encountered various issues and bugs along the way. If anyone has advice on how to successfully start a project using tailwind and react, I would apprec ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

What are the reasons for passing a global variable to a function?

Is there a difference between the two ways of writing this code? First Method: (function(i) { // Manipulate i here }(global_variable)) Second Method: (function() { // Manipulate global_variable here }()) What's the reason for passing a gl ...

v-bind is not recognizing modifications in the array elements (vue js)

I'm currently working on switching the id of an image upon the user clicking a button. At first, the id should be set to B0_h, but once the user clicks the button, it should trigger a change in an array value to true. Initially, all values in the arra ...

Transferring information from Django function to Javascript without the need for refreshing the page

I am currently working with a Django function. @csrf_exempt def postdata(request): r = requests.post(url ,headers=headers, auth=auth, data=json.dumps(data)) return HttpResponse(r) My goal is to pass the variable 'r', which contains a di ...

The Math.random() function is responsible for producing a single random number

I have a unique idea for a keyboard that generates divs when keys are pressed. The keyboard functionality has already been implemented. Each div should be positioned randomly on the screen but still be grouped by letter. My approach involves adding a rando ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

Changing text array to field identifiers with JavaScript

Is there an elegant way in ECMAScript 6 to transform a string array generated from a map function into field names within a dynamically created object? For instance, if I receive the following output from my map function: ["checkbox1Value", "checkbox4Val ...

Disable password styling in Angular by changing the type attribute to "none."

I'm curious about something, I want to add a checkbox in my application that can toggle the visibility of the password input field. HTML <input type="text" ng-model="data.username" placeholder="username" value="username" class="form-control" popo ...

html organizing elements with columns and flexbox

Is there a way to design an input box with a button aligned on the left, but not contained within the input box itself? I'm seeking guidance on crafting an input box and button pair that both perfectly fit within the dimensions of a div. The input bo ...

Structuring Server Side Code with Node.js and Express

I am faced with the task of restructuring my server and its components. My goal is to streamline the process by segregating different functionalities. app.post("/login", function(request, response) { }); app.post("/register", function(request, response) ...

Adding data to an array using V-Bind in VueJS

I am currently working on a project that involves retrieving data from multiple devices and displaying the data on a chart in real-time. The goal is to update the chart every second as new data comes in. Below is the code snippet I have been using: index ...

Exclusive to Firefox: The left and right arrows will shift the entire page

I've encountered a strange issue with my website that only seems to be occurring in Firefox. When using the mouse scroll, I am able to move up and down as expected. However, when using the arrow keys, the entire page shifts to the right in approximate ...

Create a file with jQuery and send it to PHP

Hello everyone, I am currently in the process of developing a website that has the ability to generate an MS Excel file using jQuery and allow users to download it. My question is, how can I pass this generated file to PHP so that it can be sent as an atta ...

What causes Font Awesome 5 icons to vanish when changing the font-family?

I am facing an issue with the code I have below. It changes the font style successfully, but it also causes the icon to disappear. Can anyone provide tips on how to ensure that the icon remains visible while changing the font style? <link rel="styles ...