Reordering table columns with react via drag and drop

HaNdTriX picture HaNdTriX · Nov 21, 2016 · Viewed 7.2k times · Source

I have an html table that should be able to reorder rows as well as columns.

enter image description here

Reordering rows is pretty straight forward but reordering columns is pretty hard since the cells of a column do not share the same parent element.

<table>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
  </tr>
  <tr>
    <td>Col 1</td>
    <td>Col 2</td>
  </tr>
</table>

How do I implement column-dragging with react?

Answer

Oleg Imanilov picture Oleg Imanilov · Nov 21, 2016

You should add additional layer of abstraction between data and view - where column indexes will be used. For example:

var data : [["a","b","c"],["a2","b2","c2"]];
var columns = [2,1,0];

function getData(row, col) {
   return data[row][columns[col]];
}

Then when you drag columns - you just change indexes inside columns var.