This Post explains how to sort table rows by drag and drop in LWC. Below is the demo of output :
Drag_Drop_Sorting.html :
<template>
<div class="container">
<template for:each={ElementList} for:item="Elements">
<tr key={Elements.Id}>
<th
key={Elements}
style="padding:10px;background-color:#a6a5a3;"
class="Items"
onchange={Change}
draggable="true"
ondrop={Drop}
ondragstart={DragStart}
ondragover={DragOver}>
{Elements}
</th>
</tr>
</template>
</div>
</template>
Drag_Drop_Sorting.js
import { LightningElement, track } from 'lwc';
export default class Drag_Drop_Sorting extends LightningElement {
Data = [];
@track ElementList = ['1st : Apex Salesfore', '2nd : Lightning Web Component', '3rd :
Aura Component', '4th : Salesforce Admin', '5th : LoveSalesforceYes']
connectedCallback(){
if(!this.ElementList){
this.ElementList = [...this.Data]
}
}
Change(event){
this.Data = event.detail.join(', ');
}
DragStart(event) {
event.target.classList.add('drag')
}
DragOver(event) {
event.preventDefault()
return false
}
Drop(event) {
event.stopPropagation()
const Element = this.template.querySelectorAll('.Items')
const DragValName = this.template.querySelector('.drag').textContent
const DropValName = event.target.textContent
if(DragValName === DropValName){ return false }
const index = this.ElementList.indexOf(DropValName)
this.ElementList = this.ElementList.reduce((acc, curVal, CurIndex) => {
if(CurIndex === index){
return [...acc, DragValName, curVal]
}
else if(curVal !== DragValName){
return [...acc, curVal]
}
return acc
}, [])
Element.forEach(element => {
element.classList.remove('drag')
})
return this.ElementList
}
}
Drag_Drop_Sorting.Meta
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Hi,
ReplyDeleteI am trying to achieve it for images.
But const DragValName = this.template.querySelector('.drag').textContent
DragValName is coming null for my case.
I want achieve this functionality on Contact records data table using AURA component.
ReplyDeletecould you please provide how can I do this ?
Maybe the following code could help you i guess,
Deletehttps://github.com/yasarshaikh/LWCDraggableDataTable
I realized you have to drop the dragging item one more item below the target one, when dragging and dropping from top to bottom.
ReplyDeleteI fixed that issue by comparing the index of the dragging value against the index of the dropping value:
if(CurIndex === index){
if(dragIndex > dropIndex){
return [...acc, DragValName, curVal];
}else{
return [...acc, curVal, DragValName];
}
}
Nice! Thanks!
DeleteYour Fixed is not working. When place this chunk of code it given error dragIndex is undefined
ReplyDelete