Search code examples
reactjsantd

How can I pass a className to the Header of a Table in antd / Ant Design?


With an Ant Design Table, I can pass a className to an arbitrary row using the rowClassName prop:

rowClassName={(record, index) => index === 0 && 'headerClassName'}

Is there any way to do this with the Header?


Solution

  • It seems that CSS is quite tricky when it comes to styling tables, and the antd Table is built with regular HTML tables (with logical sugar on top). It isn't possible to pass a className to the header of a table with antd, but it also seems like that wouldn't be the most useful if we could.

    Instead, the solution is to pass the className to the Table as a whole, and have CSS as follows in order to style the header.

    import React from 'react';
    import { Table } from 'antd';
    import { css } from 'react-emotion';
    
    const tableCSS = css({
      margin: '40px 120px',
      backgroundColor: 'white',
      '& table': {
        borderCollapse: 'collapse'
      },
      '& thead > tr > th': {
        backgroundColor: 'darkblue',
        color: 'white',
      },
      '& thead > tr': {
        borderWidth: '2px',
        borderColor: 'yellow',
        borderStyle: 'solid'
      }
    });
    
    const StyledTable = ({ data, columns }) => (
        <Table
          className={tableCSS}
          dataSource={data}
          columns={columns}
        />
    );
    

    Note: You only need the borderCollapse: 'collapse' if you want a border that's around the header row.