Define custom column size with react-table

131 views Asked by At

I'm using the @tanstack/react-table library to manage the rendering of a table. I would like to manage the width of some specific columns but as react-table is a headless library I ended up with such code:

  <table>
    <thead>
      {table.getHeaderGroups().map((headerGroup) => (
        <tr key={headerGroup.id}>
          {headerGroup.headers.map((header) => {
            return (
              <th
                key={header.id}
                colSpan={header.colSpan}
                style={{
                  width:
                    header.id === "action"
                      ? "6rem"
                      : header.id === "ID"
                      ? "4rem"
                      : "auto",
                }}
              >
              ...  

Maintaining the style of the th element isn't really great and I'd like to find a way of defining these sizes in the declaration of my columns.

Would you have a more elegant solution?

Here is a codesandbox: Edit react-table-header-size

1

There are 1 answers

0
Manu Benjamin On

You can define the size attribute in the columns json like below,

const columns = [
  {
    accessorKey: 'col1',
    size: 270, //set column size for this column
  },
  {
    accessorKey: 'col2',
    size: 200, //set column size for this column
  }, 
]

Modify your React table component and add the min-width property if there is a size attribute defined for that column.

<table>
<thead>
  {table.getHeaderGroups().map((headerGroup) => (
    <tr key={headerGroup.id}>
      {headerGroup.headers.map((header) => {
        return (
          <th
            key={header.id}
            colSpan={header.colSpan}
            style={{
              minWidth: header.getSize() ? header.getSize() : 0
            }}
          >

Follow these links for the official guide,

https://tanstack.com/table/v8/docs/guide/column-sizing#column-sizing-guide https://tanstack.com/table/v8/docs/api/features/column-sizing#column-def-options