react-table - How to fix width of th elements

6.5k views Asked by At

I using react-table and I want to use table-layout: fixed.

I would like to specify the width of the columns using classNames.

Is there any way react-table allows to set a fix width for some columns ? If not, How could I add classNames to <th> elements ?

This issue resolves adding classNames to cells https://github.com/tannerlinsley/react-table/issues/1612 but not for <th> elements.

What would it be a viable way?

ps: I would like to avoid using :nth-child selector since I dont want to have a dependency to columns position on the table.

1

There are 1 answers

0
kitimenpolku On BEST ANSWER

Ok, I found an answer when reviewing examples code.

https://react-table-omega.vercel.app/docs/examples/data-driven-classes-and-styles

The solution is by defining extra properties in the column:

{
  Header: 'Name',
  columns: [
    {
      Header: 'First Name',
      accessor: 'firstName',
      className: 'user',
    },
  ],
},

This information will be available in column. Now we can pass these information to the column.getHeaderProps([....]). It will take into account the props we passed.

 <tr {...headerGroup.getHeaderGroupProps()}>
   {headerGroup.headers.map(column => (
     <th {...column.getHeaderProps([
       { className: column.className },
     ])}>
       {column.render('Header')}
     </th>
   ))}
 </tr>

In ghis way, <th> can receive the props we set in columns array.