In the case of sorting by default in React Table, there are a couple of issues to work/sort out. But unlike some other answers, you dont need to use local state or anything besides React Table hooks and props. This answers only your sorting question, not filtering:
disableSortRemove: true
is a React Table prop; and adding it gets you to a place of, on the very first click you'll still have an "unsorted" state, and then subsequent clicks are sorted asc or desc, as opposed to the default behavior, which on a third click gets you back to an "unsorted" state. That's perhaps not the UI you want, as a button click, first or not, should do something, but with that one variable, on first click it wont.
You want two columns sorted by default, and only sort asc or desc, so you need a couple more elements in place. Here's what your setup may look like.
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable(
{
columns: tableColumns,
data: tableData,
disableSortRemove: true,
defaultCanSort: true,
initialState: {
sortBy: [{ id: tableData[0]?.totalSeries?.series, desc: true }], // IMPORTANT: Use your own data structure and add as many columns that need sorting by default
},
},
useSortBy
);
Here we've added 3 things rather than just the one disableSortRemove: true
. We've added:
disableSortRemove: true
,
defaultCanSort: true
,
and initialState: { sortBy: [{ id: tableData[0]?.totalSeries?.series, desc: true }] },
I don't think you need the second one (defaultCanSort: true
) BUT the first and third give you the effect you want: On page load, sorting is on and once you click the sort button it sorts the opposite way. The two columns you add to the initialState
array will be sorted by default.
Done. Sorted.