Created
May 9, 2017 21:12
-
-
Save mattlockyer/2ece67a544c4e062411328144dabc9da to your computer and use it in GitHub Desktop.
React Component for Draggable Re-ordering of Columns in react-table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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
Have you submitted this to
react-table
as a PR? I would think that it would be welcomed