I had a slightly different use case and wanted to get multi-sorting by default on initial load, but then also keep that sorting order behind any future sorts
sandbox example here:
https://codesandbox.io/s/goofy-shadow-9tskr?file=/src/App.js
The trick is NOT using the built in getSortByToggleProps() and instead adding your own onClick that uses the setSortBy func.
Below code inspired from @khai nguyen's answer
import React from 'react'
import { useTable, useSortBy } from 'react-table';
function Table({ columns, data, sortBy ...rest }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
setSortBy,
} = useTable({
columns,
data,
initialState: {sortBy}
})
}, useSortBy);
Then in your column header element:
...PREV_TABLE_CODE
{headerGroup.headers.map(column => (
<th
{...column.getHeaderProps()}
onClick={() => handleMultiSortBy(column, setSortBy, sortBy)}
>
{column.render(
REST_TABLE_CODE....
and the handleMultiSortByCode (my custom function, not from react-table):
isSortedDesc can be either true/false/undefined
export const handleMultiSortBy = (column, setSortBy, meinSortBy) => {
//set sort desc, aesc or none?
const desc =
column.isSortedDesc === true
? undefined
: column.isSortedDesc === false
? true
: false;
setSortBy([{ id: column.id, desc }, ...meinSortBy]);
};
Note: The default toggleSortBy() func had a e.persist() in it. I'm not sure what function it served, but not using it doesn't have any ill effects that I've noticed - the stock multi-sort doesn't work (holding shift) but adding it back didn't fix that. Suspect you might need the stock toggleSort for that.