0

I am using Ant Design V2.X and I cannot update to a newer version. I inherited code and I am struggling to sort the data according to certain column. It should be ordered once, and not sorted dynamically.

This is what I have within the return() function of my React component:

<Table size="small"
       dataSource={this.props.Data}
       rowKey={(record) => (record.LedgerId * 100 + record.PositionId).toString()}
       pagination={false}
       showHeader={true}
>

I was assuming the rowKey would order my data according to the arrow-function, but this is not the case. Can you all guide me how to solve this?

Background info

Within the component, I have the following declaration:

export interface ViewTableProps {   
    selectedEntity: number,
    Data Interfaces.ViewEntry[],
}

and elsewhere

export interface ViewEntry {
    //Id: number,
    LedgerId: number,
    PositionId: number,
    Value: number,
    children: ViewEntry[]
}

Related and not-so related posts

B--rian
  • 5,578
  • 10
  • 38
  • 89

2 Answers2

2

If you want to add actual sorters to your individual columns, you'd need to write sort functions in the sorter property of your column definitions. If you want to sort the entire dataset by default, you could sort the dataSource before passing it to the table.

Column sort from their docs:

{
    title: 'Age',
    dataIndex: 'age',
    defaultSortOrder: 'descend',
    sorter: (a, b) => a.age - b.age,
  },

If you want a "default sort," you can just make a function to sort data outside the table;

const sortData = (data) => {
   // Call slice to create a new Array and prevent mutating it if it's stored in state
   return data.slice().sort((a, b) => a.myKey - b.myKey);
}

...

<Table size="small"
       dataSource={sortData(this.props.Data)}
       rowKey={(record) => (record.LedgerId * 100 + record.PositionId).toString()}
       pagination={false}
       showHeader={true}
>

Chris B.
  • 5,477
  • 1
  • 12
  • 30
0

If you would like to order dates, I recommend this:

import moment from 'moment';

and add

{
 title: 'Date',
 dataIndex: 'date',
 key: "date",
 sorter: (a, b) => moment(a.date).unix() - moment(b.date).unix()
},
  • 1
    Add MomentJS for something that can be archived by in build JS Date is unnecessary and affects the overall bundle size. It adds a large chunk to the overall vender file. – Pramod Mali Aug 28 '20 at 05:05