There is many cases when we need to create a table in a website and need column resize on those tables, how we can do that?
NPM Grid Packages
There are many NPM grid packages with inbuilt resize feature in it, we can use one of those packages, But what is the problem?.
Any drawbacks?
Yes, This packages comes with lot more features that we don’t possibly need (Pagination, sort, virtualise). So why we need to create such a large package just to have the resize, do we have any other options
CSS Resize
resize: horizontal;
Yes, we can use ‘resize’ in CSS for enabling the resize for any element, so do it can be applied for table cell to. But is that have anything missing?. Ya kind off
What is missing in CSS resize?
Yes, CSS resize can’t be controlled much from a script, like in resize there will be a resize icon that we can’t style also a min-width and max-width for a cell while resize can’t be controlled from CSS resize.
Is there any solution?. Yes
Solution
We can create a element in each table cell for resize and then user hold and drag this element, we need to adjust with of the table cell just prior to the element. Because this is in table style all cells will auto adjust to the the size as we adjust one cell width.
import React from "react";
import { render } from "react-dom";
const App = () => {
return(
<div>
<table class="column_resize_table">
<thead>
<tr>
<th>Headding 1</th>
// resize element
<th onMouseMove={onMouseMove} class="resize-th"/>
<th>Headding 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
<td />
<td>Content 2</td>
</tr>
</tbody>
</table>
</div>
)
};
render(<App />, document.body);
function onMouseMove(e) {
const moveDiff = this.startPos - this.mouseX;
let newPrev = this.startWidthPrev - moveDiff;
ele.previousSibling.style.width = newPrev + 'px';
ele.previousSibling.style.minWidth = newPrev + 'px';
ele.previousSibling.style.maxWidth = newPrev + 'px';
}
Okey, Now we need to control the min-width and max-width
function onMouseMove(e, minWidth, maxWidth) {
const moveDiff = this.startPos - this.mouseX;
let newPrev = this.startWidthPrev - moveDiff;
if((!minWidth || newPrev >= minWidth) && (!maxWidth || newPrev <= maxWidth)) {
ele.previousSibling.style.width = newPrev + 'px';
ele.previousSibling.style.minWidth = newPrev + 'px';
ele.previousSibling.style.maxWidth = newPrev + 'px';
}
}
So we can set all this features in this resize element, but the TH element we created will act as a column itself, so we need to control its width, how we can do that?, Style the resize element.
.resize-th {
cursor: ew-resize;
width: 3px; // Change as per the UI
min-width: 3px;
max-width: 3px;
}
Conclusion
So we done that, we can resize a table cell without over complicating and with all the features we need. For implementing this and with some more additional features check out my NPM package.
Comments are closed