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>(null);
39
40 const shownProducts = useMemo(() => {
41 if (!sorting) {
42 return products
43 }
44 return products.slice().sort((a, b) => {
45 // @ts-ignore
46 const aVal = a[sorting.id]
47 // @ts-ignore
48 const bVal = b[sorting.id]
49 if (aVal < bVal) {
50 return sorting.desc ? 1 : -1
51 }
52 if (aVal > bVal) {
53 return sorting.desc ? -1 : 1
54 }
55 return 0
56 })
57 }, [sorting])
58
59 const table = useDataTable({
60 data: shownProducts,
61 columns,
62 getRowId: (product) => product.id,
63 rowCount: products.length,
64 sorting: {
65 // Pass the pagination state and updater to the table instance
66 state: sorting,
67 onSortingChange: setSorting,
68 },
69 isLoading: false,
70 })
71
72 return (
73 <DataTable instance={table}>
74 <DataTable.Toolbar className="flex justify-between items-center">
75 <Heading>Products</Heading>
76 {/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}
77 <DataTable.SortingMenu tooltip="Sort" />
78 </DataTable.Toolbar>
79 <DataTable.Table />
80 </DataTable>
81 );
82 };