Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Created May 9, 2017 21:12
Show Gist options
  • Save mattlockyer/2ece67a544c4e062411328144dabc9da to your computer and use it in GitHub Desktop.
Save mattlockyer/2ece67a544c4e062411328144dabc9da to your computer and use it in GitHub Desktop.
React Component for Draggable Re-ordering of Columns in react-table
import React, { Component } from 'react';
import ReactTable, { ReactTableDefaults } from 'react-table';
//https://github.com/tannerlinsley/react-table
//https://react-table.js.org/
import 'react-table/react-table.css'
Object.assign(ReactTableDefaults, {
defaultPageSize: 10,
minRows: 3,
});
class Table extends Component {
constructor(props) {
super(props);
this.dragged = null;
this.reorder = [];
this.state = {
trigger:0
};
}
mountEvents() {
const headers = Array.prototype.slice.call(document.querySelectorAll('.rt-th'));
headers.forEach((header, i) => {
header.setAttribute('draggable', true);
//the dragged header
header.ondragstart = (e) => {
e.stopPropagation;
this.dragged = i;
};
header.ondrag = (e) => e.stopPropagation;
header.ondragend = (e) => {
e.stopPropagation;
setTimeout(() => this.dragged = null, 100);
};
//the dropped header
header.ondragover = (e) => {
e.preventDefault();
};
header.ondrop = (e) => {
e.preventDefault();
const { target, dataTransfer } = e;
this.reorder.push({ a: i, b: this.dragged });
this.setState({ trigger: Math.random() });
};
});
}
componentDidMount() {
this.mountEvents();
}
render() {
const { rows, fieldMap } = this.props;
//fieldMap is a parallel array to headers, stores row object field names
const columns = this.props.headers.map((k, i) => ({
header: k,
accessor: fieldMap[i]
}));
//run all reorder events
this.reorder.forEach(o => columns.splice(o.a, 0, columns.splice(o.b, 1)[0]));
//render
return (<div className="esr-table">
<ReactTable
data={rows}
columns={columns}
/>
</div>);
}
}
export default Table;
@ayxos
Copy link

ayxos commented Sep 26, 2018

Can you provide an implementation example with mocked props?

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