Skip to content

Commit

Permalink
Updated Table sorting demo (#3090)
Browse files Browse the repository at this point in the history
* memo: Updated Table sorting demo

* refactor: use nullish check for sortable

* Update aksel.nav.no/website/pages/eksempler/table/sortable.tsx

Co-authored-by: Halvor Haugan <[email protected]>

---------

Co-authored-by: Halvor Haugan <[email protected]>
  • Loading branch information
KenAJoh and HalvorHaugan authored Aug 13, 2024
1 parent d319dae commit d4ce6ae
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions aksel.nav.no/website/pages/eksempler/table/sortable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ import { useState } from "react";
import { SortState, Table } from "@navikt/ds-react";
import { withDsExample } from "@/web/examples/withDsExample";

interface ScopedSortState extends SortState {
orderBy: keyof (typeof data)[0];
}

const Example = () => {
const [sort, setSort] = useState<SortState | undefined>();
const [sort, setSort] = useState<ScopedSortState | undefined>();

const handleSort = (sortKey) => {
const handleSort = (sortKey: ScopedSortState["orderBy"]) => {
setSort(
sort && sortKey === sort.orderBy && sort.direction === "descending"
? undefined
Expand All @@ -19,15 +23,15 @@ const Example = () => {
);
};

const comparator = (a, b, orderBy) => {
if (b[orderBy] < a[orderBy] || b[orderBy] === undefined) {
function comparator<T>(a: T, b: T, orderBy: keyof T): number {
if (b[orderBy] == null || b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
};
}

const sortedData = data.slice().sort((a, b) => {
if (sort) {
Expand All @@ -40,7 +44,12 @@ const Example = () => {

return (
<>
<Table sort={sort} onSortChange={(sortKey) => handleSort(sortKey)}>
<Table
sort={sort}
onSortChange={(sortKey) =>
handleSort(sortKey as ScopedSortState["orderBy"])
}
>
<Table.Header>
<Table.Row>
<Table.ColumnHeader sortKey="name" sortable>
Expand Down

0 comments on commit d4ce6ae

Please sign in to comment.