Corey Bruyere
Corey Bruyere

Reputation: 976

How to specify column width for first column using react-table

When using useRowSelect and useTable how can I specify column width for the first column so that it never exceeds the width of the checkboxes? I don't want to use useFlex as I want to preserve column widths based on the header width.

You'll notice when the table is set to 100% width the first column starts to grow if you expand your browser window.

Here's an example:

https://codesandbox.io/s/youthful-hamilton-j0rev?file=/src/App.js

I'm also open to just grabbing the Header and Cell from where I'm pushing into the columns array and adding a className, but wasn't able to find a way to do that. How can I add a className so that the table cell that surrounds this column data has a className to attach to:

    (hooks) => {
      isRowSelectable &&
        hooks.allColumns.push((columns) => [
          {
            id: 'selection',
            minWidth: 35,
            width: '35px',
            maxWidth: 35,
            Header: ({ getToggleAllRowsSelectedProps }) => (
              <Checkbox alignSelf="center" {...getToggleAllRowsSelectedProps()} />
            ),
            Cell: ({ row }: any) => {
              row.className = '123';
              return <Checkbox alignSelf="center" {...row.getToggleRowSelectedProps()} />;
            }
          },
          ...columns
        ]);
    }

Upvotes: 0

Views: 1253

Answers (1)

toki
toki

Reputation: 1006

Since Array.map can pass the index of the element, it's fairly simple to conditionally add a className to the cell if the row index is 0:

{
  rows.map((row, i) => {
    prepareRow(row);
    return (
      <td className={i === 0 ? "class-name" : ""} {...cell.getCellProps()>
         {cell.render("Cell")}
      </td>
    ) ​
}

If you want the same class to apply to the headers, you can do the same thing on the <th> or <tr> elements, since those are also rendered with Array.map. You don't actually need to touch the columns object at all for this change.

Upvotes: 0

Related Questions