I just came up with a very simple solution to this:
- Add the following props to your th element:
<th
{...column.getHeaderProps()}
{...column.getHeaderProps(column.getSortByToggleProps())}
// THESE
data-column-index={i}
draggable="true"
onDragStart={onDragStart}
onDragOver={e => e.preventDefault()}
onDrop={onDrop}
>
{column.render('Header')}
</th>
- Then, add these vars and functions to your component:
let columnBeingDragged = null;
const onDragStart = e => {
columnBeingDragged = e.target.dataset.columnIndex;
};
const onDrop = e => {
e.preventDefault();
const newPosition = e.target.dataset.columnIndex;
const currentCols = visibleColumns.map(c => c.id);
const colToBeMoved = currentCols.splice(columnBeingDragged, 1);
currentCols.splice(newPosition, 0, colToBeMoved[0]);
setColumnOrder(currentCols);
};
Styles and improvements are up to you. :)
My gist: https://gist.github.com/anacampesan/aaf842c47506ad5d87842e7c82196482
Most helpful comment
Hi
I took @mattlockyer example and made a HOC. I made a little changes.With the original I was just able to drag and drop just one time.
You can see the code here: https://codesandbox.io/s/5vxlnjrw1n