Question

How to do default sorting in react-table

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

 46  99406  46
1 Jan 1970

Solution

 76

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
                }
            ]
        }
    }
2020-04-17

Solution

 21

For those using V8 and want to avoid the frustration I went to to find the answer in the docs, you simply provide your initial state into the useState that V8 uses for sorting:

Instead of the default:

const [sorting, setSorting] = useState<SortingState>([]);

You would do:

const [sorting, setSorting] = useState<SortingState>([
    {id: "time", desc: true}
]);
2023-02-26