table icon indicating copy to clipboard operation
table copied to clipboard

Column resizing doesn't respect `clientWidth`, bad experience with limited width tables

Open Faithfinder opened this issue 1 year ago • 2 comments

TanStack Table version

8.20.6

Framework/Library version

18.3

Describe the bug and the steps to reproduce it

Take the official full width resizable table example https://tanstack.com/table/v8/docs/framework/react/examples/full-width-resizable-table

With limited screen space, grow a column, and then grow it some more. You'll notice that the state now has a ridiculous amount of width, while the column is still fairly small visually. This means that to size it down_ you now need to drag the handle left a lot without much result.

The solution would be to detect that dragging is over and set the column size to the header element's clientWidth, but I'm not entirely sure how to achieve that.

Your Minimal, Reproducible Example - (Sandbox Highly Recommended)

https://tanstack.com/table/v8/docs/framework/react/examples/full-width-resizable-table

Screenshots or Videos (Optional)

Image

Do you intend to try to help solve this bug with your own PR?

No, because I do not have time to dig into it

Terms & Code of Conduct

  • [x] I agree to follow this project's Code of Conduct
  • [x] I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.

Faithfinder avatar Jan 16 '25 22:01 Faithfinder

The reason this "dead zone" / ghost dragging happens in constrained or full-width layouts is a mismatch between two separate sizing layers:

  1. State layer (TanStack Table): columnSizing stores raw cumulative pixel offsets calculated directly from event.clientX - startX. It increments indefinitely without knowing anything about DOM boundaries or parent container limits.
  2. Layout layer (Browser CSS): Because the table is styled with width: 100% / table-layout: fixed or inside a container without overflow-x: auto, the browser's layout engine forcibly clamps the rendered <th> width.

If the DOM width is clamped at 180px but the user continues dragging right, TanStack's state inflates to 500px. When dragging back left, nothing moves visually until the internal state drops below 180px.

Here are the two ways to solve this cleanly:


Solution 1: Sync Sizing State with DOM clientWidth on Drag End

Attach a ref to the <th> cell and wrap the resize handler so that once dragging completes (mouseup/touchend), the column's sizing entry in state is clamped to the actual rendered DOM width (getBoundingClientRect().width):

function ResizableHeader({ header, table }: { header: Header<any, unknown>; table: Table<any> }) {
  const thRef = useRef<HTMLTableCellElement>(null);

  const handleMouseDown = (e: React.MouseEvent) => {
    const defaultHandler = header.getResizeHandler();
    defaultHandler(e);

    const onMouseUp = () => {
      window.removeEventListener('mouseup', onMouseUp);
      // Wait for layout paint to finalize
      requestAnimationFrame(() => {
        if (thRef.current) {
          const renderedWidth = Math.round(thRef.current.getBoundingClientRect().width);
          table.setColumnSizing((prev) => ({
            ...prev,
            [header.column.id]: renderedWidth,
          }));
        }
      });
    };

    window.addEventListener('mouseup', onMouseUp);
  };

  return (
    <th
      ref={thRef}
      style={{
        width: header.getSize(),
        position: 'relative',
      }}
    >
      {flexRender(header.column.columnDef.header, header.getContext())}
      <div
        onMouseDown={handleMouseDown}
        onTouchStart={header.getResizeHandler()}
        className={`resizer ${header.column.getIsResizing() ? 'isResizing' : ''}`}
      />
    </th>
  );
}

Solution 2: Dynamic maxSize Constraint Based on Container Width

If you want to prevent the ghost dragging during the drag (rather than just reconciling on mouse up), enforce an upper bound via maxSize derived from the available container width:

const containerRef = useRef<HTMLDivElement>(null);

// In your column definitions or table options:
const availableWidth = containerRef.current?.clientWidth ?? 1200;
const defaultMinSize = 50;

// A single column cannot visually grow larger than (ContainerWidth - sum of minSize of other visible columns)
const maxAllowableSize = availableWidth - (visibleColumnsCount - 1) * defaultMinSize;

// In table options:
defaultColumn: {
  minSize: 50,
  maxSize: maxAllowableSize,
}

Solution 3: Proper Overflow Architecture (Recommended for Data-Dense Tables)

If columns are expected to expand freely, the table element itself should be driven by table.getTotalSize() inside an overflow wrapper rather than constrained by width: 100%:

<div style={{ width: '100%', overflowX: 'auto' }}>
  <table style={{ width: table.getTotalSize(), tableLayout: 'fixed' }}>
    {/* headers and rows */}
  </table>
</div>

When width: table.getTotalSize() is on the <table> element with horizontal scrolling enabled, DOM widths match the TanStack internal pixel calculations 1:1, eliminating clamping artifacts entirely.

amasen02 avatar Sep 20 '26 15:09 amasen02

Still reproduces on @tanstack/react-table v8.21.3 (latest npm @tanstack/react-table@8, 2026-10-20).

Ran a minimal inline demo with the same columnResizeMode: "onChange" setup as the official full-width-resizable-table example:

  1. Drag First Name resize handle rightward three times in a row. After each drag the column visually stays near the viewport edge, but the columnSizing state keeps accumulating: {fn: 660} → {fn: 1160} → {fn: 1261}.
  2. After drag 3 the column appears capped at the viewport right edge, but columnSizing.fn (1261) is larger than the rendered column width — the extra state is invisible.
  3. Dragging the handle 600 px back leftward must first consume that excess before the visual width changes, producing the dead-zone described in the original report.

22-second recording (annotated with the live columnSizing readout): https://scenerecap.com/s/4c21g2d53o

scenerecap avatar Oct 20 '26 08:10 scenerecap