How to resize columns with React Table Hooks with a specific table width

20.6k Views Asked by At

I'm trying to implement the resizing feature with React-Table and the Hook useResizeColumns. I want to force the table to take always the full width of its container. Only the columns should change theirs size. Not the table. If you take a look into this example that I made here. (Codesandbox) You can easily resize the column to surpass the red container. And for some reason if you minimize the columns size, the table will fit always the container !

I don't understand the behavior here. Any ideas ? Thank you very much.

3

There are 3 best solutions below

6
On

Found the fix. You need to fix your css for table to have display:inline-block;. It is weird that a css fixes the issue :-). You can see the fixed issue over here https://codesandbox.io/s/react-table-with-full-width-forked-rbi6u

 .table {
  border: 2px red solid;
  display:inline-block;
}

Please try the sandbox again as I had missed saving the fix in codesandbox.

2
On

If you want a CSS solution, you have two options. Option #1 is probably what you want, but your intention is a bit unclear, so I've included a second option, just in case I've misunderstood your intention.

Option #1: (Give the table a scrollbar, mimicking the behavior most React tables seem to prefer.)

.table {
    overflow: auto;
}

or Option #2: (Shrink the columns to fit within the table)

.td, .th, .tr {
    flex-shrink: 1 !important;
    min-width: auto !important;
}
0
On

You need to set the max width for the table. You can use this code.

const defaultColumn = React.useMemo(
    () => ({
      width: 100,
      minWidth: 50,
      maxWidth: 100
    }),
    []
  );

  const { headerGroups, rows, prepareRow } = useTable(
    {
      columns,
      data,
      defaultColumn
    },
    useResizeColumns,
    useFlexLayout
  );

After altering this, the table stays within its container.

Source:

https://codesandbox.io/s/intelligent-brook-0qicz?file=/src/App.js:1187-1314