javascriptreactjssortingreact-tablereact-table-v7

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


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?


Solution

  • I managed to do this by passing a controlled state into my table as suggested here:

    https://react-table.tanstack.com/docs/faq#how-can-i-manually-control-the-table-state