diff --git a/app/examples/sorting/SortingExample.tsx b/app/examples/sorting/SortingExample.tsx index a1442004..64e30768 100644 --- a/app/examples/sorting/SortingExample.tsx +++ b/app/examples/sorting/SortingExample.tsx @@ -6,6 +6,7 @@ import { useEffect, useState } from 'react'; import { type Company, companies } from '~/data'; export default function SortingExample() { + // third sorting click will cause the column to go back to unsorted state by making columnAccessor = "" const [sortStatus, setSortStatus] = useState>({ columnAccessor: 'name', direction: 'asc', @@ -13,6 +14,10 @@ export default function SortingExample() { const [records, setRecords] = useState(sortBy(companies, 'name')); useEffect(() => { + if (!sortStatus.columnAccessor) { + setRecords(companies); + return; + } const data = sortBy(companies, sortStatus.columnAccessor) as Company[]; setRecords(sortStatus.direction === 'desc' ? data.reverse() : data); }, [sortStatus]); diff --git a/app/examples/sorting/page.tsx b/app/examples/sorting/page.tsx index badafaf5..8f685028 100644 --- a/app/examples/sorting/page.tsx +++ b/app/examples/sorting/page.tsx @@ -40,6 +40,11 @@ export default async function SortingExamplePage() { sortable column header is clicked. + + Clicking a sorted column header a third time clears its sorting: onSortStatusChange is called with{' '} + columnAccessor set to an empty string, while direction resets to 'asc'. + Handle this case in your own sorting logic, as shown in the example below. + If you enable sorting, you might want to consider{' '} diff --git a/package/DataTableHeaderCell.tsx b/package/DataTableHeaderCell.tsx index 4a8cacf4..465c8b51 100644 --- a/package/DataTableHeaderCell.tsx +++ b/package/DataTableHeaderCell.tsx @@ -88,10 +88,10 @@ export function DataTableHeaderCell({ sortable && onSortStatusChange ? (e?: React.BaseSyntheticEvent) => { if (e?.defaultPrevented) return; - + const hasCycledBackToAsc = sortStatus?.direction === 'desc'; onSortStatusChange({ sortKey, - columnAccessor: accessor, + columnAccessor: sortStatus?.columnAccessor === accessor && hasCycledBackToAsc ? '' : accessor, direction: sortStatus?.columnAccessor === accessor ? sortStatus.direction === 'asc'