How to do default sorting in react-table

Blessy Julie picture Blessy Julie · Feb 6, 2020 · Viewed 22.6k times · Source

I am using react-table v7 https://www.npmjs.com/package/react-table for creating tables.

  1. I am able to do sorting to all the columns by referring this example of sorting https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting . Now I dont want all columns to sort but some specfic columns and I want to sort 2 columns by default descending. Can someone please help me with this.

  2. After applying filters to the table I want to clear all the applied filters. Can someone please help in solving this issue too ?

Thank you

Answer

Chuck L picture Chuck L · Apr 17, 2020

The other answer given was for react-table that didn't use react hooks (< v7). In order to sort a column (or columns) when the table is built, you just have to set the sortBy array on the initialState in the useTable hook.

const {
    getTableProps,
    getTableBodyProps,
    ...
} = useTable(
    {
        columns,
        ....,
        initialState: {
            sortBy: [
                {
                    id: 'columnId',
                    desc: false
                }
            ]
        }
    }