Reorder Rows Using Drag and Drop in LWC Data Table

In Salesforce Lightning Data tables, we can add a drag-and-drop feature to arrange the rows in the data table. This will allow dynamic reordering of records directly within the UI of the Lightning data table.

In this Salesforce tutorial, we will learn how to reorder rows using drag-and-drop in the LWC data table.

Create an LWC Data Table with a Drag-and-Drop Feature in Salesforce

In the example below, we will create a lightning data table that will display account records, where we can rearrange the records in the table with drag and drop.

  1. First, create the controller class from which we will fetch the account records.
public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Industry, Phone FROM Account LIMIT 10];
    }
}
  1. Now, enter the code below in the HTML file to render the UI of the data table.
<template>
    <div class="slds-grid slds-grid_vertical">
      <div class="slds-scrollable slds-grow">
        <div class="slds-scrollable_none">
          <table
            aria-multiselectable="true"
            class="
              slds-table slds-no-row-hover
              slds-table_bordered
              slds-table_fixed-layout
              slds-table_resizable-cols "
            role="grid">
            <thead>
              <tr class="slds-line-height_reset">
                <th>Account Name</th>
                <th>Account Phone</th>
                <th>Account Industry</th>
              </tr>
            </thead>
            <tbody>
              <template for:each={ElementList} for:item="acc" for:index="index">
                <tr
                  key={acc.Id}
                  onchange={Change}
                  draggable="true"
                  ondrop={Drop}
                  ondragstart={DragStart}
                  ondragover={DragOver}
                  title={index}>
                  <td role="gridcell">
                    <div class="slds-cell-wrap" title={index}>{acc.Name}</div>
                  </td>
                  <td role="gridcell">
                    <div class="slds-cell-wrap" title="Phone">{acc.Phone}</div>
                  </td>
                  <td role="gridcell">
                    <div class="slds-cell-wrap" title="Industry">{acc.Industry}</div>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </template>

In this HTML template, we have used SLDS classes for styling, with a scrollable container using “slds-scrollable slds-grow,” a header row (Account Name, Phone, Industry), and a body that iterates over elementList to create draggable rows with event handlers (ondragstart, ondragover, ondrop) and a data-index attribute for tracking.

  1. After this, enter the code below in the JS file to define the functionality of the drag and drop feature in the Lightning data table.
import { LightningElement, wire, track } from "lwc";
import getAccountList from "@salesforce/apex/AccountController.getAccounts";

export default class DragandDropTable extends LightningElement {
  @track dragStart;
  @track ElementList = [];

  connectedCallback() {
    getAccountList()
      .then((result) => {
        for (let i = 0; i < result.length; i++) {
          this.ElementList.push(result[i]);
        }
      })
      .catch((error) => {
        console.log("Error : " + error.body.message);
      });
  }
  DragStart(event) {
    this.dragStart = event.target.title;
    event.target.classList.add("drag");
  }

  DragOver(event) {
    event.preventDefault();
    return false;
  }

  Drop(event) {
    event.stopPropagation();
    const DragValName = this.dragStart;
    const DropValName = event.target.title;
    if (DragValName === DropValName) {
      return false;
    }
    const index = DropValName;
    const currentIndex = DragValName;
    const newIndex = DropValName;
    Array.prototype.move = function (from, to) {
      this.splice(to, 0, this.splice(from, 1)[0]);
    };
    this.ElementList.move(currentIndex, newIndex);
  }
}

In this, we have defined the methods to implement the drag and drop function in the data table. The handleDragStart function triggers when we drag a row. It allows the component to move the row, then saves the row’s position number in draggedIndex using the data-index value, and adds a ‘dragging‘ style to the row so we can see it’s being moved.

The handleDragOver method enables dropping by preventing the default behaviour (not moving rows) and setting the drop effect to ‘move,’ ensuring the drag will move rows to a valid drop target.

After this, the handledrop function runs when you drop a row to a new point. It stops default actions, gets the drop position, and reorders the table data by moving the row and updating the display if it’s different from the start point.

  1. After this, enter the code below in the meta.xml file to expose the LWC component to the Lightning pages.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Go to the Lightning page where you need to deploy the Lightning data table, click on the settings icon, and select the Edit page.
  1. In the Lightning App Builder, drag the LWC component to the page region and save the changes.
Reorder Rows with drag and drop in LWC data table

Now, on the lightning page, we can arrange the row positions with drag and drop.

How to arrange rows with drag and drop in LWC data table

This way, we can implement the drag-and-drop function in the LWC Lightning Data Table and arrange the rows in the table using drag-and-drop.

Conclusion

In this Salesforce tutorial, we have learned how to reorder rows using drag-and-drop in the LWC data table. To implement the drag and drop feature, we have drag and drop event handlers in the JS file to handle the dynamic reordering logic.

By using the draggable attribute and event handlers like ondragstart, ondragover, and ondrop, we enabled users to rearrange rows within the Lightning data table UI by dragging them from one point to another.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.