Skip to content

Instantly share code, notes, and snippets.

@anacampesan
Created March 30, 2020 19:38
Show Gist options
  • Save anacampesan/aaf842c47506ad5d87842e7c82196482 to your computer and use it in GitHub Desktop.
Save anacampesan/aaf842c47506ad5d87842e7c82196482 to your computer and use it in GitHub Desktop.
Column Drag & Drop Reordering - react-table
// In your component, add this var and functions:
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);
};
// In the TH element, add the following props:
<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>
@dkumar431
Copy link

Do you have a code sandbox example?

@ViieeS
Copy link

ViieeS commented Oct 22, 2020

Do you have a code sandbox example?

The solution is based on this example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment