Search code examples
reactjsantd

How to prevent sorting for some specific rows in antd table?


I am using Antd table in my react project. There are some grouped rows in the table.

So, my tableData:

const dataSource = [...groupedData, ...nonGroupedData];

I want to prevent sorting in groupedData rows. So, Client, Campaign, and Plan rows always be in the top and sorting should not affect those. Only the rows below the grouped rows need to be sorted. How to achieve that behavior?

Codepen Demo

enter image description here


Solution

  • Antd Table has no such a feature to force rows on top.

    YOu can alter your sorter function to force some on top.

    For example, lets add a forceOnTop: true on the nonGroupedData:

    {
          key: "3",
          name: "Item 1",
          id: "11",
          from: "2011-12-24 23:12:00",
          to: "2012-12-24 23:12:00",
          forceOnTop: true
    }
    

    Then we can alter the sorter function to force those with that flag on top:

    const columns = [
        {
          title: "Name",
          dataIndex: "name",
          key: "name",
          sorter: (a, b) => (a?.forceOnTop) ? 0 : a.name.localeCompare(b.name)
        },
        ...
    

    Were each row that returns 0 will be forced on top, or use the localCompare for all other rows.