2

I have implement an Ant Design Table in a Gatsby site. I am pulling in the data from graphql. So far everything has worked just fine. The data is displaying properly, pagination works, etc.

Now I want to add the ability to sort the columns. To do so, I set up the table and columns as follows:

<Table
  dataSource={data.allNewsFeed.edges}
  onChange={onChange}
  rowSelection={rowSelection}
  rowKey="id"
>
  <Column
    title="Title"
    dataIndex="node.title"
    key="title"
    sorter={(a, b) => a.node.title - b.node.title}
    sortDirections={["descend", "ascend"]}
  />
</Table>

Now, the icon for sorting the column does shows up, but nothing happens when I click on it.

Same thing happens if I remove .node from the sorter function: sorter={(a, b) => a.title - b.title}.

So, I am stuck -- any idea why this is not working and how to fix it?

Thanks.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
Moshe
  • 6,011
  • 16
  • 60
  • 112
  • Does this answer your question? [how to sort a table in alphabetical order with antd](https://stackoverflow.com/questions/55808128/how-to-sort-a-table-in-alphabetical-order-with-antd) – core114 Dec 25 '20 at 07:44

2 Answers2

3

I guess you can use instead of a.node.title - b.node.title the String.prototype.localeCompare for proper sorting. As the documentation states:

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

Somehow this:

const values = ['random', 'something', 'else', 'text'];
const result = values.sort((a,b) => {
  return a.localeCompare(b);
});

console.log(result);

So I guess in the mentioned case it would be:

<Column title="Title"
        dataIndex="node.title"
        key="title"
        sorter={(a, b) => a.node.title.localeCompare(b.node.title)}
        sortDirections={["descend", "ascend"]} />

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
3

@norbitrial's answer is correct, as for reference here is a generic sorter (for numbers and strings):

const sorter = (a, b) => (isNaN(a) && isNaN(b) ? (a || '').localeCompare(b || '') : a - b);
// Usage example with antd table column
[
  {
    title: 'Status',
    dataIndex: 'status',
    key: 'status',
    width: '10%',
    // status can be Number or String
    sorter: (a, b) => sorter(a.status, b.status),
    render: Name
  }
]
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118