Skip to content

Instantly share code, notes, and snippets.

@vontell068
Created April 24, 2018 06:18
Show Gist options
  • Save vontell068/05351150d66efcb8ad747d093ea0eb56 to your computer and use it in GitHub Desktop.
Save vontell068/05351150d66efcb8ad747d093ea0eb56 to your computer and use it in GitHub Desktop.
ResizableTable.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Table } from 'antd';
import uuidV4 from 'uuid/v4';
class ResizableTable extends React.Component {
constructor(props) {
super(props);
this.table = null;
this.column = null;
this.tableWidth = 0;
}
componentDidMount() {
let el = ReactDOM.findDOMNode(this);
this.table = el.getElementsByTagName('table')[0];
this.table.setAttribute('data-table-resizable', 'true');
let id = `rs-tb-${uuidV4()}`;
this.table.id = id;
this.resizeable();
this.clearColumnsWidth();
}
resizeable() {
const cells = this.table.rows[0].cells;
Array.prototype.forEach.call(cells, (cell) => {
cell.addEventListener('mousedown', this.handleMousedown);
cell.addEventListener('mousemove', this.handleMousemove, true);
});
this.table.addEventListener('mouseup', this.handleMouseup);
}
handleMousedown = (event) => {
let target = event.currentTarget;
if (event.offsetX > target.offsetWidth - 10) {
target.mouseDown = true;
target.oldX = event.x;
target.oldWidth = target.offsetWidth;
}
this.column = target;
this.tableWidth = this.table.rows[0].clientWidth;
}
handleMousemove = (event) => {
let target = event.currentTarget;
if (event.offsetX > target.offsetWidth - 10) {
target.style.cursor = 'col-resize';
} else {
target.style.cursor = 'default';
}
if (!this.column) {
this.column = target;
}
let column = this.column;
if (column.mouseDown) {
column.style.cursor = 'default';
var diff = (event.x - column.oldX);
if (column.oldWidth + (event.x - column.oldX) > 0) {
column.width = column.oldWidth + diff;
}
column.style.width = column.width;
column.style.cursor = 'col-resize';
}
}
handleMouseup = () => {
if (this.column) {
this.column.mouseDown = false;
this.column.style.cursor = 'default';
}
}
clearColumnsWidth() {
let colgroup = null;
let childNodes = this.table.childNodes;
childNodes.forEach(node => {
if (node.tagName === 'COLGROUP') {
colgroup = node;
}
});
if (colgroup) {
colgroup.childNodes.forEach(node => {
node.style.width = 'auto';
});
}
}
render() {
return <Table {...this.props} bordered />;
}
}
export default ResizableTable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment