Problem Description:
I’m experiencing inconsistent behavior with multi-sorting in React Table v8. The issue occurs specifically when sorting different columns:
Scenario 1 (Not Working):
First sort by name “name” (string values)
Then add second sort by “process_sheet_required” column (boolean values)
Result: Sorting doesn’t work correctly
Scenario 2 (Working):
First sort by “process_sheet_required” column (boolean values)
Then add second sort by “name” column (string values)
Result: Sorting works as expected
Current Implementation:
type Props<T extends Entities> = {
data: T[];
columns: StrictColumnDef<T>[];
entity: string;
defaultSorting?: SortingState;
handleNew?: () => void;
};
const Table = <T extends Entities>({
data,
columns,
entity,
handleNew,
defaultSorting,
}: Props<T>) => {
const memoData = useMemo(() => data, [data]);
const { t } = useTranslation();
const [sorting, setSorting] = useState<SortingState>(() => {
return defaultSorting ? [...defaultSorting] : [];
});
const [isColumnsModalOpen, setIsColumnsModalOpen] = useState(false);
const sortingFn = useCallback(
(rowA: Row<T>, rowB: Row<T>, columnId: string): number => {
const a = rowA.getValue(columnId);
const b = rowB.getValue(columnId);
// Manejo de valores nulos o undefined
if (a === null || a === undefined)
return b === null || b === undefined ? 0 : 1;
if (b === null || b === undefined) return -1;
// Si son booleanos, manejarlos directamente
if (typeof a === "boolean" && typeof b === "boolean") {
return a === b ? 0 : a ? -1 : 1;
}
// Para strings, usar localeCompare
if (typeof a === "string" && typeof b === "string") {
return a.localeCompare(b);
}
// Convertir otros tipos a string para comparación consistente
return String(a).localeCompare(String(b));
},
[]
);
const table = useReactTable({
data: memoData,
columns,
state: {
sorting,
},
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
isMultiSortEvent: () => true,
sortDescFirst: false,
enableMultiSort: true,
sortingFns: {
custom: sortingFn,
},
defaultColumn: {
sortingFn: sortingFn,
},
});
Question:
Why does the multi-sort behavior differ depending on which column is sorted first? How can I achieve consistent multi-sorting regardless of the column order?
Environment:
React Table v8
TypeScript
React 18
The problem in detail:
When I’m trying the scenario 1 it seems to add the column to the ordered columns array and the icon in the column header changes as well, but, if you look at the results, there is no change in the order
But, if I try with the second scenario, everything works fine: