Search code examples
javascriptreactjsantd

Antd table how to fixed first row


I am working with Ant Design table component. The problem is, how do it fix the first table row?

Illustration of table


Solution

  • You can achieve this effect by using children headers, and then styling the child header to look like a fixed first row.

    See example I put together here:

    Codepen

    Cheers!

    code:

    const {  Table  } = antd;
    
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name1',
            children: [
          {
            title: 'Summary',
            dataIndex: 'name',
            key: 'name2',
          },
        ],
        sorter: (a, b) => a.name - b.name
      },
      {
        title: 'Age',
        children: [
          {
            dataIndex: 'age',
            key: 'age',
          },
        ],
         sorter: (a, b) => a.age - b.age
    
      },
      {
        title: 'Company',
        children: [
          {
            dataIndex: 'companyAddress',
            key: 'companyAddress',
          },
        ],
      },
      {
        title: 'Gender',
        dataIndex: 'gender',
        key: 'gender',
         children: [
          {
            dataIndex: 'age',
            key: 'age',
          },
        ],
      },
    ];
    
    const data = [];
    for (let i = 0; i < 100; i++) {
      data.push({
        key: i,
        name: 'John Brown',
        age: i + 1,
        street: 'Lake Park',
        building: 'C',
        number: 2035,
        companyAddress: 'Lake Street 42',
        companyName: 'SoftLake Co',
        gender: 'M',
      });
    }
    
    ReactDOM.render(
      <Table
        columns={columns}
        dataSource={data}
        bordered
        size="middle"
        scroll={{ x: 'calc(700px + 50%)', y: 240 }}
      />,
      mountNode,
    );```