`react-table` v7 how to preserve a grouping's sort order whilst the rows of the groups are sorted

Viewed 1806

I have a table that is grouped with an initial sort order applied.

I want to be able to sort on the UI but at the same time preserve the initial grouping sort order.

So it would be like a multi-sort but that one sorting rule is always applied to the group.

This is the initial sorting rule:

  const initialSortBy: Array<RisksIdentifiedSortBy> = [
    {
      id: DataAccessors.RISK_SCORE,
      desc: true,
    },
    {
      id: DataAccessors.GROUP,
      desc: false,
    },
  ];

RISK_SCORE column would be sortable:

{
    Header: (): JSX.Element => {
      return (
        <Box sx={{ margin: 'auto' }}>
          {t('policy-management/summary:TABLE.HDR.RISK_SCORE')}
        </Box>
      );
    },
    accessor: DataAccessors.RISK_SCORE,
    sortType: 'alphanumeric',
    Cell: ({
      value,
      row,
    }: DataTableCell<RiskLevel>): JSX.Element | null => {
      return !row.canExpand ? (
      ...
      ) : null;
    },
  },

And we would force RISK_GROUP to be sorted the same every time without being sortable itself from user interaction:

  {
    Header: t('policy-management/summary:TABLE.HDR.RISK_GROUP'),
    accessor: DataAccessors.GROUP,
    Cell: ({ value }: DataTableCell<string>): string => value,
    SubCell: ({ row }: Pick<DataTableCell<any>, 'row'>): JSX.Element => {
      const {
        original: { riskCategory },
      } = row;
      return <Box sx={{ ml: '1.5rem' }}>{riskCategory}</Box>;
    },
    width: '20%',
    disableSortBy: true,
  },

Any ideas how to do this?

I think it would be similar to programmatically setting the sort option in one column when another is sorted?

3 Answers
useTable({ columns, data, autoResetSortBy: false }, useSortBy))

i was stuck with this for a while, turns out there is a property on table instance

const tableInstance = useTable<any>(
    { columns, data: memoData, autoResetExpanded: false, autoResetSortBy: false }, ...)

docs:

autoResetSortBy: Boolean

Defaults to true When true, the sortBy state will automatically reset if any of the following conditions are met: data is changed To disable, set to false For more information see the FAQ "How do I stop my table state from automatically resetting when my data changes?"

https://react-table.tanstack.com/docs/api/useSortBy

Related