简体   繁体   中英

antd table, disable unsorted option for a column (force sort)

To enable sort on a column, using the sortDirections parameter with values ['ascend', 'descend'] . With this setting there are 3 sorting options: 'ascend', 'descend', 'unsorted'.

Is there a simple way to force sorting, remove the unsorted option?

For example:

Given a list of unsorted numbers [1, 5 ,2 ,10] . Currently, I can set sortDirections with values ['ascend', 'descend'] . This will provide 3 options, sort in ascending order, sort in descended order AND unsorted, eg same as the original numbers.

Desired behavior:

I would like to force sort, meaning I don't want the 'unsorted' option to be available. If the user clicks the column header, the whole column should be sorted either in ascending order or in descended order.

From theDocumentation but actually helpful.

"You can set as ['ascend', 'descend', 'ascend'] to prevent sorter back to default status."

I've been poking around too and there is no way (as of now) of customizing the column header sorting behavior to ignore the unsorted state. Moreover, the developers clearly state that they want to sticky with this way here:

https://github.com/ant-design/ant-design/issues/12905

@mkkekkonen make sure you used the docs before pointing to it...

I have recently wanted similar behavior, and I did the following and it works fine.

const [sort, setSort] = useState('ascend');

{
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
      sorter: (a, b) => a.age - b.age,
      sortOrder: sort,
      onHeaderCell: () => ({
        onClick: () => setSort(sort === 'ascend' ? 'descend' : 
      'ascend'),       
      sortDirections: ['ascend', 'descend', 'ascend'],
      }),
},

From thedocumentation :

sortDirections: ['ascend' | 'descend'] sortDirections: ['ascend' | 'descend'] defines available sort methods for each columns, effective for all columns when set on table props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM