简体   繁体   中英

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

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.

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

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM