Raw
1 ---
2 generate_toc: true
3 ---
4
5 import { ComponentExample } from "@/components/ComponentExample"
6 import { ComponentReference } from "@/components/ComponentReference"
7 import { Feedback } from "@/components/Feedback"
8
9 export const metadata = {
10 title: `Data Table`,
11 }
12
13 # {metadata.title}
14
15 A component to display a table of data with advanced functionalities like pagination, filtering, and more.
16
17 In this guide, you'll learn how to use the DataTable component.
18
19 The `DataTable` component is useful if you're displaying large data with functionalities like pagination, filtering, sorting, and searching. It's also the recommended table component to use when creating customizations in the Medusa Admin.
20
21 <Note>
22
23 This component is available after Medusa UI v4.0.4 (or Medusa v2.4.0). It is built on top of the [Table](../table/page.mdx) component. If you want a table with more control over its styling and functionality, use that component instead.
24
25 </Note>
26
27 <ComponentExample name="data-table-demo" disableCenterAlignPreview />
28
29 ## Usage
30
31 You import the `DataTable` component from `@medusajs/ui`.
32
33 ```tsx
34 import {
35 DataTable,
36 } from "@medusajs/ui"
37 ```
38
39 ### Data Table Columns Preparation
40
41 Before using the `DataTable` component, you need to prepare its columns using the `createDataTableColumnHelper` utility:
42
43 ```tsx
44 import {
45 // ...
46 createDataTableColumnHelper,
47 } from "@medusajs/ui"
48
49 const data = [
50 {
51 id: "1",
52 title: "Shirt",
53 price: 10,
54 },
55 // other data...
56 ]
57
58 const columnHelper = createDataTableColumnHelper<typeof data[0]>()
59
60 const columns = [
61 columnHelper.accessor("title", {
62 header: "Title",
63 enableSorting: true,
64 }),
65 columnHelper.accessor("price", {
66 header: "Price",
67 }),
68 ]
69 ```
70
71 The `createDataTableColumnHelper` utility is a function that returns a helper used to generate column configurations for the `DataTable` component.
72
73 For each column in the table, use the `accessor` method of the column helper to specify configurations for a specific column. The `accessor` method accepts the column's key in the table's data as the first parameter, and an object with the following properties as the second parameter:
74
75 - `header`: The table header text for the column.
76 - `enableSorting`: (optional) A boolean that indicates whether data in the table can be sorted by this column. More on sorting in [this section](#configure-sorting-in-datatable).
77
78 ### Create Data Table Instance
79
80 The `DataTable` component expects a table instance created using the `useDataTable` hook. Import that hook from `@medusajs/ui`:
81
82 ```tsx
83 import {
84 // ...
85 useDataTable,
86 } from "@medusajs/ui"
87 ```
88
89 Then, inside the component that will render `DataTable`, create a table instance using the `useDataTable` hook:
90
91 ```tsx
92 export default function ProductTable() {
93 const table = useDataTable({
94 columns,
95 data,
96 getRowId: (product) => product.id,
97 rowCount: data.length,
98 isLoading: false,
99 })
100 }
101 ```
102
103 The `useDataTable` hook accepts an object with the following properties:
104
105 - `columns`: An array of column configurations generated using the `createDataTableColumnHelper` utility.
106 - `data`: The data to be displayed in the table.
107 - `getRowId`: A function that returns the unique identifier of a row. The identifier must be a string.
108 - `rowCount`: The total number of rows in the table. If you're fetching data from the Medusa application with pagination or filters, this will be the total count, not the count of the data returned in the current page.
109 - `isLoading`: A boolean that indicates whether the table is loading data. This is useful when loading data from the Medusa application for the first time or in between pages.
110
111 ### Render DataTable
112
113 Finally, render the `DataTable` component with the table instance created using the `useDataTable` hook:
114
115 ```tsx
116 export default function ProductTable() {
117 // ...
118 return (
119 <DataTable instance={table}>
120 <DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
121 <Heading>Products</Heading>
122 </DataTable.Toolbar>
123 <DataTable.Table />
124 </DataTable>
125 )
126 }
127 ```
128
129 In the `DataTable` component, you pass the following child components:
130
131 1. `DataTable.Toolbar`: The toolbar component shown at the top of the table. You can also add buttons for custom actions.
132 2. `DataTable.Table`: The table component that renders the data.
133
134 Refer to the examples later on this page to learn how to add pagination, filtering, and other functionalities using the `DataTable` component.
135
136 ---
137
138 ## API Reference
139
140 <ComponentReference mainComponent="DataTable" componentsToShow={[
141 "DataTable",
142 "DataTable.Table",
143 "DataTable.Pagination",
144 "DataTable.FilterMenu",
145 "DataTable.Search",
146 "DataTable.CommandBar",
147 "DataTable.SortingMenu",
148 ]} />
149
150 ---
151
152 ## Example with Data Fetching
153
154 Refer to [this Admin Components guide](https://docs.medusajs.com/resources/admin-components/guides/data-table) for an example on using the `DataTable` component with data fetching from the Medusa application.
155
156 ---
157
158 ## Handle Row Click
159
160 <ComponentExample name="data-table-row-click" disableCenterAlignPreview />
161
162 In many cases, you want to perform an action when a row is clicked. Most commonly, you may want to open the details page of the row when it's clicked.
163
164 <Note>
165
166 For bulk actions, such as deleting multiple rows, use the [Command Bar](#perform-bulk-actions-on-datatable-rows) instead.
167
168 </Note>
169
170 The `useDataTable` hook accepts an `onRowClick` property that you can use to handle row clicks:
171
172 ```tsx
173 const navigate = useNavigate()
174
175 const table = useDataTable({
176 // ...
177 onRowClick(event, row) {
178 navigate(`/author/${row.id}`)
179 },
180 })
181 ```
182
183 The value of `onRowClick` is a function that accepts two parameters:
184
185 - `event`: An instance of the [MouseEvent](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) object.
186 - `row`: The data of the row that was clicked.
187
188 In the above example, you use a `navigate` function, retrieved through the `useNavigate` hook from `react-router-dom`, to navigate to the details page of the row that was clicked.
189
190 ---
191
192 ## Configure Cell Rendering
193
194 <ComponentExample name="data-table-custom-cell" disableCenterAlignPreview />
195
196 The `accessor` method of the `createDataTableColumnHelper` utility accepts a `cell` property that you can use to customize the rendering of the cell content.
197
198 For example:
199
200 ```tsx
201 const products = [
202 {
203 id: "1",
204 title: "Shirt",
205 price: 10,
206 is_active: true,
207 },
208 {
209 id: "2",
210 title: "Pants",
211 price: 20,
212 is_active: true,
213 },
214 ]
215
216 const columnHelper = createDataTableColumnHelper<typeof products[0]>()
217
218 const columns = [
219 columnHelper.accessor("is_active", {
220 header: "Status",
221 cell: ({ getValue }) => {
222 const isActive = getValue()
223 return (
224 <Badge color={isActive ? "green" : "grey"}>
225 {isActive ? "Active" : "Inactive"}
226 </Badge>
227 )
228 },
229 }),
230 // ...
231 ]
232 ```
233
234 The `cell` property's value is a function that returns a string or a React node to be rendered in the cell. The function receives as a parameter an object having a `getValue` property to get the raw value of the cell.
235
236 ---
237
238 ## Configure Search in DataTable
239
240 <ComponentExample name="data-table-search" disableCenterAlignPreview />
241
242 The object passed to the `useDataTable` hook accepts a `search` property that you can use to enable and configure the search functionality in the `DataTable` component:
243
244 ```tsx
245 // `useState` imported from `React`
246 const [search, setSearch] = useState("")
247
248 const table = useDataTable({
249 // ...
250 search: {
251 state: search,
252 onSearchChange: setSearch,
253 },
254 })
255 ```
256
257 `search` accepts the following properties:
258
259 - `state`: The search query string. This must be a React state variable, as its value will be used for the table's search input.
260 - `onSearchChange`: A function that updates the search query string. Typically, this would be the setter function of the state variable, but you can also perform custom actions if necessary.
261
262 Next, you must implement the search filtering. For example, if you're retrieving data from the Medusa application, you pass the search query to the API to filter the data.
263
264 For example, when using a simple array as in the example above, this is how you filter the data by the search query:
265
266 ```tsx
267 const [search, setSearch] = useState<string>("")
268
269 const shownProducts = useMemo(() => {
270 return products.filter((product) => product.title.toLowerCase().includes(search.toLowerCase()))
271 }, [search])
272
273 const table = useDataTable({
274 columns,
275 data: shownProducts,
276 getRowId: (product) => product.id,
277 rowCount: products.length,
278 isLoading: false,
279 // Pass the state and onSearchChange to the table instance.
280 search: {
281 state: search,
282 onSearchChange: setSearch,
283 },
284 })
285 ```
286
287 Then, render the `DataTable.Search` component as part of the `DataTable`'s children:
288
289 ```tsx
290 return (
291 <DataTable instance={table}>
292 <DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
293 <Heading>Products</Heading>
294 {/* This component renders the search bar */}
295 <DataTable.Search placeholder="Search..." />
296 </DataTable.Toolbar>
297 <DataTable.Table />
298 </DataTable>
299 )
300 ```
301
302 This will show a search input at the top of the table, in the data table's toolbar.
303
304 ---
305
306 ## Configure Pagination in DataTable
307
308 <ComponentExample name="data-table-pagination" disableCenterAlignPreview />
309
310 The object passed to the `useDataTable` hook accepts a `pagination` property that you can use to enable and configure the pagination functionality in the `DataTable` component.
311
312 First, import the `DataTablePaginationState` type from `@medusajs/ui`:
313
314 ```tsx
315 import {
316 // ...
317 DataTablePaginationState,
318 } from "@medusajs/ui"
319 ```
320
321 Then, create a state variable to manage the pagination:
322
323 ```tsx
324 const [pagination, setPagination] = useState<DataTablePaginationState>({
325 pageSize: 15,
326 pageIndex: 0,
327 })
328 ```
329
330 The pagination state variable of type `DataTablePaginationState` is an object with the following properties:
331
332 - `pageSize`: The number of rows to display per page.
333 - `pageIndex`: The current page index. It's zero-based, meaning the first page would be `0`.
334
335 Next, pass the pagination object to the `useDataTable` hook:
336
337 ```tsx
338 const table = useDataTable({
339 // ...
340 pagination: {
341 state: pagination,
342 onPaginationChange: setPagination,
343 },
344 })
345 ```
346
347 `pagination` accepts the following properties:
348
349 - `state`: The pagination state object. This must be a React state variable of type `DataTablePaginationState`.
350 - `onPaginationChange`: A function that updates the pagination state object. Typically, this would be the setter function of the state variable, but you can also perform custom actions if necessary.
351
352 You must also implement the pagination logic, such as fetching data from the Medusa application with the pagination parameters.
353
354 For example, when using a simple array as in the example above, this is how you paginate the data:
355
356 ```tsx
357 const [pagination, setPagination] = useState<DataTablePaginationState>({
358 pageSize: PAGE_SIZE,
359 pageIndex: 0,
360 })
361
362 const shownProducts = useMemo(() => {
363 return products.slice(
364 pagination.pageIndex * pagination.pageSize,
365 (pagination.pageIndex + 1) * pagination.pageSize
366 )
367 }, [pagination])
368
369 const table = useDataTable({
370 data: shownProducts,
371 columns,
372 rowCount: products.length,
373 getRowId: (product) => product.id,
374 pagination: {
375 // Pass the pagination state and updater to the table instance
376 state: pagination,
377 onPaginationChange: setPagination,
378 },
379 isLoading: false,
380 })
381 ```
382
383 Finally, render the `DataTable.Pagination` component as part of the `DataTable`'s children:
384
385 ```tsx
386 return (
387 <DataTable instance={table}>
388 <DataTable.Toolbar>
389 <Heading>Products</Heading>
390 </DataTable.Toolbar>
391 <DataTable.Table />
392 {/** This component will render the pagination controls **/}
393 <DataTable.Pagination />
394 </DataTable>
395 )
396 ```
397
398 This will show the pagination controls at the end of the table.
399
400 ---
401
402 ## Configure Filters in DataTable
403
404 <ComponentExample name="data-table-filters" disableCenterAlignPreview />
405
406 The object passed to the `useDataTable` hook accepts a `filters` property that you can use to enable and configure the filtering functionality in the `DataTable` component.
407
408 First, add the following imports from the `@medusajs/ui` package:
409
410 ```tsx
411 import {
412 // ...
413 createDataTableFilterHelper,
414 DataTableFilteringState,
415 } from "@medusajs/ui"
416 ```
417
418 The `createDataTableFilterHelper` utility is a function that returns a helper function to generate filter configurations for the `DataTable` component. The `DataTableFilteringState` type is an object that represents the filtering state of the table.
419
420 Then, create the filters using the `createDataTableFilterHelper` utility:
421
422 <Note title="Tip">
423
424 Create the filters outside the component rendering the `DataTable` component.
425
426 </Note>
427
428 ```tsx
429 const filterHelper = createDataTableFilterHelper<typeof products[0]>()
430
431 const filters = [
432 filterHelper.accessor("title", {
433 type: "select",
434 label: "Title",
435 options: products.map((product) => ({
436 label: product.title,
437 value: product.title.toLowerCase(),
438 })),
439 }),
440 ]
441 ```
442
443 The filter helper returned by `createDataTableFilterHelper` has an `accessor` method that accepts the column's key in the data as the first parameter, and an object with the following properties as the second parameter:
444
445 - `type`: The type of filter. It can be either:
446 - `select`: A select dropdown filter.
447 - `radio`: A radio button filter.
448 - `date`: A date filter.
449 - `label`: The label text for the filter.
450 - `options`: If the filter type is `select` or `radio`, an array of dropdown options. Each option has a `label` and `value` property.
451
452 <Note>
453
454 Refer to [this section](#filtering-date-values) to learn how to use date filters.
455
456 </Note>
457
458 Next, in the component rendering the `DataTable` component, create a state variable to manage the filtering, and pass the filters to the `useDataTable` hook:
459
460 ```tsx
461 const [filtering, setFiltering] = useState<DataTableFilteringState>({})
462
463 const table = useDataTable({
464 // ...
465 filters,
466 filtering: {
467 state: filtering,
468 onFilteringChange: setFiltering,
469 },
470 })
471 ```
472
473 You create a `filtering` state variable of type `DataTableFilteringState` to manage the filtering state. You can also set initial filters as explained in [this section](#initial-filter-values).
474
475 The `useDataTable` hook accepts the following properties for filtering:
476
477 - `filters`: An array of filter configurations generated using the `createDataTableFilterHelper` utility.
478 - `filtering`: An object with the following properties:
479 - `state`: The filtering state object. This must be a React state variable of type `DataTableFilteringState`.
480 - `onFilteringChange`: A function that updates the filtering state object. Typically, this would be the setter function of the state variable, but you can also perform custom actions if necessary.
481
482 You must also implement the logic of filtering the data based on the filter conditions, such as sending the filter conditions to the Medusa application when fetching data.
483
484 For example, when using a simple array as in the example above, this is how you filter the data based on the filter conditions:
485
486 ```tsx
487 const [filtering, setFiltering] = useState<DataTableFilteringState>({})
488
489 const shownProducts = useMemo(() => {
490 return products.filter((product) => {
491 return Object.entries(filtering).every(([key, value]) => {
492 if (!value) {
493 return true
494 }
495 if (typeof value === "string") {
496 // @ts-ignore
497 return product[key].toString().toLowerCase().includes(value.toString().toLowerCase())
498 }
499 if (Array.isArray(value)) {
500 // @ts-ignore
501 return value.includes(product[key].toLowerCase())
502 }
503 if (typeof value === "object") {
504 // @ts-ignore
505 const date = new Date(product[key])
506 let matching = false
507 if ("$gte" in value && value.$gte) {
508 matching = date >= new Date(value.$gte as number)
509 }
510 if ("$lte" in value && value.$lte) {
511 matching = date <= new Date(value.$lte as number)
512 }
513 if ("$lt" in value && value.$lt) {
514 matching = date < new Date(value.$lt as number)
515 }
516 if ("$gt" in value && value.$gt) {
517 matching = date > new Date(value.$gt as number)
518 }
519 return matching
520 }
521 })
522 })
523 }, [filtering])
524
525 const table = useDataTable({
526 data: shownProducts,
527 columns,
528 getRowId: (product) => product.id,
529 rowCount: products.length,
530 isLoading: false,
531 filtering: {
532 state: filtering,
533 onFilteringChange: setFiltering,
534 },
535 filters,
536 })
537 ```
538
539 When filters are selected, the `filtering` state object will contain the filter conditions, where the key is the column key and the value can be:
540
541 - `undefined` if the user is still selecting the value.
542 - A string if the filter type is `radio`, as the user can choose only one value.
543 - An array of strings if the filter type is `select`, as the user can choose multiple values.
544 - An object with the filter conditions if the filter type is `date`. The filter conditions for dates are explained more in [this section](#filtering-date-values).
545
546 Finally, render the `DataTable.FilterMenu` component as part of the `DataTable`'s children:
547
548 ```tsx
549 return (
550 <DataTable instance={table}>
551 <DataTable.Toolbar className="flex justify-between items-center">
552 <Heading>Products</Heading>
553 {/** This component will render a menu that allows the user to choose which filters to apply to the table data. **/}
554 <DataTable.FilterMenu tooltip="Filter" />
555 </DataTable.Toolbar>
556 <DataTable.Table />
557 </DataTable>
558 )
559 ```
560
561 This will show a filter menu at the top of the table, in the data table's toolbar.
562
563 ### Filtering Date Values in DataTable
564
565 <ComponentExample name="data-table-filters-date" disableCenterAlignPreview />
566
567 Consider your data has a `created_at` field that contains date values. To filter the data based on date values, you can add a `date` filter using the filter helper:
568
569 ```tsx
570 const filters = [
571 // ...
572 filterHelper.accessor("created_at", {
573 type: "date",
574 label: "Created At",
575 format: "date",
576 formatDateValue: (date) => date.toLocaleString(),
577 rangeOptionStartLabel: "From",
578 rangeOptionEndLabel: "To",
579 rangeOptionLabel: "Between",
580 options: [
581 {
582 label: "Today",
583 value: {
584 $gte: new Date(new Date().setHours(0, 0, 0, 0)).toString(),
585 $lte: new Date(new Date().setHours(23, 59, 59, 999)).toString(),
586 },
587 },
588 {
589 label: "Yesterday",
590 value: {
591 $gte: new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000).toString(),
592 $lte: new Date(new Date().setHours(0, 0, 0, 0)).toString(),
593 },
594 },
595 {
596 label: "Last Week",
597 value: {
598 $gte: new Date(new Date().setHours(0, 0, 0, 0) - 7 * 24 * 60 * 60 * 1000).toString(),
599 $lte: new Date(new Date().setHours(0, 0, 0, 0)).toString(),
600 },
601 },
602 ],
603 }),
604 ]
605 ```
606
607 When the filter type is `date`, the filter configuration object passed as a second parameter to the `accessor` method accepts the following properties:
608
609 - `format`: The format of the date value. It can be either `date` to filter by dates, or `datetime` to filter by dates and times.
610 - `formatDateValue`: A function that formats the date value when displaying it in the filter options.
611 - `rangeOptionStartLabel`: (optional) The label for the start date input in the range filter.
612 - `rangeOptionEndLabel`: (optional) The label for the end date input in the range filter.
613 - `rangeOptionLabel`: (optional) The label for the range filter option.
614 - `options`: By default, the filter will allow the user to filter between two dates. You can also set this property to an array of filter options to quickly choose from. Each option has a `label` and `value` property. The `value` property is an object that represents the filter condition. In this example, the filter condition is an object with a `$gte` property that specifies the date that the data should be greater than or equal to. Allowed properties are:
615 - `$gt`: Greater than.
616 - `$lt`: Less than.
617 - `$lte`: Less than or equal to.
618 - `$gte`: Greater than or equal to.
619
620 When the user selects a date filter option, the `filtering` state object will contain the filter conditions, where the key is the column key and the value is an object with the filter conditions. You must handle the filter logic as explained earlier.
621
622 For example, when using a simple array as in the example above, this is how you filter the data based on the date filter conditions:
623
624 ```tsx
625 const shownProducts = useMemo(() => {
626 return products.filter((product) => {
627 return Object.entries(filtering).every(([key, value]) => {
628 if (!value) {
629 return true
630 }
631 // other types checks...
632 if (typeof value === "object") {
633 // @ts-ignore
634 const date = new Date(product[key])
635 let matching = false
636 if ("$gte" in value && value.$gte) {
637 matching = date >= new Date(value.$gte as number)
638 }
639 if ("$lte" in value && value.$lte) {
640 matching = date <= new Date(value.$lte as number)
641 }
642 if ("$lt" in value && value.$lt) {
643 matching = date < new Date(value.$lt as number)
644 }
645 if ("$gt" in value && value.$gt) {
646 matching = date > new Date(value.$gt as number)
647 }
648 return matching
649 }
650 })
651 })
652 }, [filtering])
653 ```
654
655 ### Initial Filter Values in DataTable
656
657 <ComponentExample name="data-table-filters-initial" disableCenterAlignPreview />
658
659 If you want to set initial filter values, you can set the initial state of the `filtering` state variable:
660
661 ```tsx
662 const [filtering, setFiltering] = useState<DataTableFilteringState>({
663 title: ["shirt"],
664 })
665 ```
666
667 The user can still change the filter values, but the initial values will be applied when the table is first rendered.
668
669 ---
670
671 ## Configure Sorting in DataTable
672
673 <ComponentExample name="data-table-sorting" disableCenterAlignPreview />
674
675 The object passed to the `useDataTable` hook accepts a `sorting` property that you can use to enable and configure the sorting functionality in the `DataTable` component.
676
677 First, in the `columns` array created by the columns helper, specify for the sortable columns the following properties:
678
679 ```tsx
680 const columns = [
681 columnHelper.accessor("title", {
682 header: "Title",
683 // Enables sorting for the column.
684 enableSorting: true,
685 // If omitted, the header will be used instead if it's a string,
686 // otherwise the accessor key (id) will be used.
687 sortLabel: "Title",
688 // If omitted the default value will be "A-Z"
689 sortAscLabel: "A-Z",
690 // If omitted the default value will be "Z-A"
691 sortDescLabel: "Z-A",
692 }),
693 ]
694 ```
695
696 The `accessor` method of the helper function accepts the following properties for sorting:
697
698 - `enableSorting`: A boolean that indicates whether data in the table can be sorted by this column.
699 - `sortLabel`: The label text for the sort button in the column header. If omitted, the `header` will be used instead if it's a string, otherwise the accessor key (id) will be used.
700 - `sortAscLabel`: The label text for the ascending sort button. If omitted, the default value will be `A-Z`.
701 - `sortDescLabel`: The label text for the descending sort button. If omitted, the default value will be `Z-A`.
702
703 Next, in the component rendering the `DataTable` component, create a state variable to manage the sorting, and pass the sorting object to the `useDataTable` hook:
704
705 ```tsx
706 import {
707 // ...
708 DataTableSortingState,
709 } from "@medusajs/ui"
710
711 export default function ProductTable() {
712 const [sorting, setSorting] = useState<DataTableSortingState | null>(null)
713
714 const table = useDataTable({
715 // ...
716 sorting: {
717 state: sorting,
718 onSortingChange: setSorting,
719 },
720 })
721
722 // ...
723 }
724 ```
725
726 You create a state variable of type `DataTableSortingState` to manage the sorting state. You can also set initial sorting values as explained in [this section](#initial-sort-values).
727
728 The `sorting` object passed to the `useDataTable` hook accepts the following properties:
729
730 - `state`: The sorting state object. This must be a React state variable of type `DataTableSortingState`.
731 - `onSortingChange`: A function that updates the sorting state object. Typically, this would be the setter function of the state variable, but you can also perform custom actions if necessary.
732
733 You must also implement the sorting logic, such as sending the sorting conditions to the Medusa application when fetching data.
734
735 For example, when using a simple array as in the example above, this is how you sort the data based on the sorting conditions:
736
737 ```tsx
738 const [sorting, setSorting] = useState<DataTableSortingState | null>(null)
739
740 const shownProducts = useMemo(() => {
741 if (!sorting) {
742 return products
743 }
744 return products.slice().sort((a, b) => {
745 // @ts-ignore
746 const aVal = a[sorting.id]
747 // @ts-ignore
748 const bVal = b[sorting.id]
749 if (aVal < bVal) {
750 return sorting.desc ? 1 : -1
751 }
752 if (aVal > bVal) {
753 return sorting.desc ? -1 : 1
754 }
755 return 0
756 })
757 }, [sorting])
758
759 const table = useDataTable({
760 data: shownProducts,
761 columns,
762 getRowId: (product) => product.id,
763 rowCount: products.length,
764 sorting: {
765 // Pass the pagination state and updater to the table instance
766 state: sorting,
767 onSortingChange: setSorting,
768 },
769 isLoading: false,
770 })
771 ```
772
773 The `sorting` state object has the following properties:
774
775 - `id`: The column key to sort by.
776 - `desc`: A boolean that indicates whether to sort in descending order.
777
778 Finally, render the `DataTable.SortingMenu` component as part of the `DataTable`'s children:
779
780 ```tsx
781 return (
782 <DataTable instance={table}>
783 <DataTable.Toolbar className="flex justify-between items-center">
784 <Heading>Products</Heading>
785 {/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}
786 <DataTable.SortingMenu tooltip="Sort" />
787 </DataTable.Toolbar>
788 <DataTable.Table />
789 </DataTable>
790 )
791 ```
792
793 This will show a sorting menu at the top of the table, in the data table's toolbar.
794
795 ### Initial Sort Values in DataTable
796
797 <ComponentExample name="data-table-sorting-initial" disableCenterAlignPreview />
798
799 If you want to set initial sort values, you can set the initial state of the `sorting` state variable:
800
801 ```tsx
802 const [sorting, setSorting] = useState<DataTableSortingState | null>({
803 id: "title",
804 desc: false,
805 })
806 ```
807
808 The user can still change the sort values, but the initial values will be applied when the table is first rendered.
809
810 ---
811
812 ## Perform Bulk Actions on DataTable Rows
813
814 <ComponentExample name="data-table-commands" disableCenterAlignPreview />
815
816 The object passed to the `useDataTable` hook accepts a `commands` object property that you can use to add custom actions to the `DataTable` component.
817
818 First, add the following imports from `@medusajs/ui`:
819
820 ```tsx
821 import {
822 // ...
823 createDataTableCommandHelper,
824 DataTableRowSelectionState,
825 } from "@medusajs/ui"
826 ```
827
828 The `createDataTableCommandHelper` utility is a function that returns a helper function to generate command configurations for the `DataTable` component. The `DataTableRowSelectionState` type is an object that represents the row selection state of the table.
829
830 Then, in the `columns` array created by the columns helper, add a `select` column:
831
832 ```tsx
833 const columns = [
834 // Commands requires a select column.
835 columnHelper.select(),
836 // ...
837 ]
838 ```
839
840 The `select` method of the helper function adds a select column to the table. This column will render checkboxes in each row to allow the user to select rows.
841
842 Next, create the commands using the `createDataTableCommandHelper` utility:
843
844 <Note title="Tip">
845
846 Create the commands outside the component rendering the `DataTable` component.
847
848 </Note>
849
850 ```tsx
851 const commandHelper = createDataTableCommandHelper()
852
853 const useCommands = () => {
854 return [
855 commandHelper.command({
856 label: "Delete",
857 shortcut: "D",
858 action: async (selection) => {
859 const productsToDeleteIds = Object.keys(selection)
860
861 // TODO remove products from the server
862 },
863 }),
864 ]
865 }
866 ```
867
868 The `createDataTableCommandHelper` utility is a function that returns a helper function to generate command configurations for the `DataTable` component.
869
870 You create a function that returns an array of command configurations. This is useful if the command's action requires initializing other functions or hooks.
871
872 The `command` method of the helper function accepts the following properties:
873
874 - `label`: The label text for the command.
875 - `shortcut`: The keyboard shortcut for the command. This shortcut only works when rows are selected in the table.
876 - `action`: A function that performs the action when the command is executed. The function receives the selected rows as an object, where the key is the row's `id` field and the value is a boolean indicating that the row is selected. You can send a request to the server within this function to perform the action.
877
878 Then, in the component rendering the `DataTable` component, create a state variable to manage the selected rows, and pass the commands to the `useDataTable` hook:
879
880 ```tsx
881 const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>({})
882
883 const commands = useCommands()
884
885 const instance = useDataTable({
886 data: products,
887 columns,
888 getRowId: (product) => product.id,
889 rowCount: products.length,
890 isLoading: false,
891 commands,
892 rowSelection: {
893 state: rowSelection,
894 onRowSelectionChange: setRowSelection,
895 },
896 })
897 ```
898
899 You create a state variable of type `DataTableRowSelectionState` to manage the selected rows. You also retrieve the commands by calling the `useCommand` function.
900
901 The `useDataTable` hook accepts the following properties for commands:
902
903 - `commands`: An array of command configurations generated using the `createDataTableCommandHelper` utility.
904 - `rowSelection`: An object that enables selecting rows in the table. It accepts the following properties:
905 - `state`: The row selection state object. This must be a React state variable of type `DataTableRowSelectionState`.
906 - `onRowSelectionChange`: A function that updates the row selection state object. Typically, this would be the setter function of the state variable, but you can also perform custom actions if necessary.
907
908 Finally, render the `DataTable.CommandBar` component as part of the `DataTable`'s children:
909
910 ```tsx
911 return (
912 <DataTable instance={instance}>
913 <DataTable.Toolbar className="flex justify-between items-center">
914 <Heading>Products</Heading>
915 </DataTable.Toolbar>
916 <DataTable.Table />
917 {/** This component will the command bar when the user has selected at least one row. **/}
918 <DataTable.CommandBar selectedLabel={(count) => `${count} selected`} />
919 </DataTable>
920 )
921 ```
922
923 This will show a command bar when the user has selected at least one row in the table.