1 import { DataTable, DataTableSortingState, Heading, createDataTableColumnHelper, useDataTable } from "@medusajs/ui"
2 import { useMemo, useState } from "react"
3
4 const products = [
5 {
6 id: "1",
7 title: "Shirt",
8 price: 10
9 },
10 {
11 id: "2",
12 title: "Pants",
13 price: 20
14 }
15 ]
16
17 const columnHelper = createDataTableColumnHelper<typeof products[0]>()
18
19 const columns = [
20 columnHelper.accessor("title", {
21 header: "Title",
22 // Enables sorting for the column.
23 enableSorting: true,
24 // If omitted, the header will be used instead if it's a string,
25 // otherwise the accessor key (id) will be used.
26 sortLabel: "Title",
27 // If omitted the default value will be "A-Z"
28 sortAscLabel: "A-Z",
29 // If omitted the default value will be "Z-A"
30 sortDescLabel: "Z-A",
31 }),
32 columnHelper.accessor("price", {
33 header: "Price",
34 }),
35 ]
36
37 export default function ProductTable () {
38 const [sorting, setSorting] = useState<DataTableSortingState | null>({
39 id: "title",
40 desc: false,
41 })
42
43 const shownProducts = useMemo(() => {
44 if (!sorting) {
45 return products
46 }
47 return products.slice().sort((a, b) => {
48 // @ts-ignore
49 const aVal = a[sorting.id]
50 // @ts-ignore
51 const bVal = b[sorting.id]
52 if (aVal < bVal) {
53 return sorting.desc ? 1 : -1
54 }
55 if (aVal > bVal) {
56 return sorting.desc ? -1 : 1
57 }
58 return 0
59 })
60 }, [sorting])
61
62 const table = useDataTable({
63 data: shownProducts,
64 columns,
65 getRowId: (product) => product.id,
66 rowCount: products.length,
67 sorting: {
68 // Pass the pagination state and updater to the table instance
69 state: sorting,
70 onSortingChange: setSorting,
71 },
72 isLoading: false,
73 })
74
75 return (
76 <DataTable instance={table}>
77 <DataTable.Toolbar className="flex justify-between items-center">
78 <Heading>Products</Heading>
79 {/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}
80 <DataTable.SortingMenu tooltip="Sort" />
81 </DataTable.Toolbar>
82 <DataTable.Table />
83 </DataTable>
84 );
85 };