docs: add documentation for DataTable (#11095)

* docs: add documentation for DataTable

* update package versions
This commit is contained in:
Shahed Nasser
2025-01-27 11:04:46 +02:00
committed by GitHub
parent 956a50e934
commit c8fc5edadd
55 changed files with 3453 additions and 1549 deletions

View File

@@ -15,8 +15,8 @@
"dependencies": {
"@mdx-js/loader": "^3.1.0",
"@mdx-js/react": "^3.1.0",
"@medusajs/icons": "~2.0.0",
"@medusajs/ui": "~3.0.0",
"@medusajs/icons": "~2.4.0",
"@medusajs/ui": "~4.0.4",
"@next/mdx": "15.0.4",
"@react-hook/resize-observer": "^2.0.2",
"@readme/openapi-parser": "^2.5.0",

View File

@@ -204,7 +204,9 @@ export const uiRouteHighlights = [
```tsx title="src/admin/routes/brands/page.tsx" highlights={uiRouteHighlights}
import { defineRouteConfig } from "@medusajs/admin-sdk"
import { TagSolid } from "@medusajs/icons"
import { Container, Heading } from "@medusajs/ui"
import {
Container,
} from "@medusajs/ui"
import { useQuery } from "@tanstack/react-query"
import { sdk } from "../../lib/sdk"
import { useMemo, useState } from "react"
@@ -214,11 +216,6 @@ const BrandsPage = () => {
return (
<Container className="divide-y p-0">
<div className="flex items-center justify-between px-6 py-4">
<div>
<Heading level="h2">Brands</Heading>
</div>
</div>
{/* TODO show brands */}
</Container>
)
@@ -234,123 +231,7 @@ export default BrandsPage
A route's file must export the React component that will be rendered in the new page. It must be the default export of the file. You can also export configurations that add a link in the sidebar for the UI route. You create these configurations using `defineRouteConfig` from the Admin Extension SDK.
So far, you only show a "Brands" header. In admin customizations, use components from the [Medusa UI package](!ui!) to maintain a consistent user interface and design in the dashboard.
### Add Table Component
To show the brands with pagination functionalities, you'll create a new `Table` component that uses the UI package's [Table](!ui!/components/table) component with some alterations to match the design of the Medusa Admin. This new component is taken from the [Admin Components guide](!resources!/admin-components/components/table).
Create the `Table` component in the file `src/admin/components/table.tsx`:
![Directory structure of the Medusa application after adding the table component.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733472527/Medusa%20Book/brands-admin-dir-overview-4_avosrf.jpg)
```tsx title="src/admin/components/table.tsx"
import { useMemo } from "react"
import { Table as UiTable } from "@medusajs/ui"
export type TableProps = {
columns: {
key: string
label?: string
render?: (value: unknown) => React.ReactNode
}[]
data: Record<string, unknown>[]
pageSize: number
count: number
currentPage: number
setCurrentPage: (value: number) => void
}
export const Table = ({
columns,
data,
pageSize,
count,
currentPage,
setCurrentPage,
}: TableProps) => {
const pageCount = useMemo(() => {
return Math.ceil(count / pageSize)
}, [count, pageSize])
const canNextPage = useMemo(() => {
return currentPage < pageCount - 1
}, [currentPage, pageCount])
const canPreviousPage = useMemo(() => {
return currentPage - 1 >= 0
}, [currentPage])
const nextPage = () => {
if (canNextPage) {
setCurrentPage(currentPage + 1)
}
}
const previousPage = () => {
if (canPreviousPage) {
setCurrentPage(currentPage - 1)
}
}
return (
<div className="flex h-full flex-col overflow-hidden !border-t-0">
<UiTable>
<UiTable.Header>
<UiTable.Row>
{columns.map((column, index) => (
<UiTable.HeaderCell key={index}>
{column.label || column.key}
</UiTable.HeaderCell>
))}
</UiTable.Row>
</UiTable.Header>
<UiTable.Body>
{data.map((item, index) => {
const rowIndex = "id" in item ? item.id as string : index
return (
<UiTable.Row key={rowIndex}>
{columns.map((column, index) => (
<UiTable.Cell key={`${rowIndex}-${index}`}>
<>
{column.render && column.render(item[column.key])}
{!column.render && (
<>{item[column.key] as string}</>
)}
</>
</UiTable.Cell>
))}
</UiTable.Row>
)
})}
</UiTable.Body>
</UiTable>
<UiTable.Pagination
count={count}
pageSize={pageSize}
pageIndex={currentPage}
pageCount={pageCount}
canPreviousPage={canPreviousPage}
canNextPage={canNextPage}
previousPage={previousPage}
nextPage={nextPage}
/>
</div>
)
}
```
This component accepts the following props:
- `columns`: An array of the table's columns.
- `data`: The rows in the table.
- `pageSize`: The maximum number of items shown in a page.
- `count`: The total number of items.
- `currentPage`: A zero-based index of the current page.
- `setCurrentPage`: A function to change the current page.
In the component, you use the UI package's [Table](!ui!/components/table) component to display the data received as a prop in a table that supports pagination.
You can learn more about this component's implementation and how it works in the [Admin Components guide](!resources!/admin-components), which provides more examples of how to build common components in the Medusa Admin dashboard.
So far, you only show a container. In admin customizations, use components from the [Medusa UI package](!ui!) to maintain a consistent user interface and design in the dashboard.
### Retrieve Brands From API Route
@@ -359,39 +240,81 @@ You'll now update the UI route to retrieve the brands from the API route you add
First, add the following type in `src/admin/routes/brands/page.tsx`:
```tsx title="src/admin/routes/brands/page.tsx"
type Brand = {
id: string
name: string
}
type BrandsResponse = {
brands: {
id: string
name: string
}[]
brands: Brand[]
count: number
limit: number
offset: number
}
```
This is the type of expected response from the `GET /admin/brands` API route.
You define the type for a brand, and the type of expected response from the `GET /admin/brands` API route.
To display the brands, you'll use Medusa UI's [DataTable](!ui!/components/data-table) component. So, add the following imports in `src/admin/routes/brands/page.tsx`:
```tsx title="src/admin/routes/brands/page.tsx"
import {
// ...
Heading,
createDataTableColumnHelper,
DataTable,
DataTablePaginationState,
useDataTable,
} from "@medusajs/ui"
```
You import the `DataTable` component and the following utilities:
- `createDataTableColumnHelper`: A utility to create columns for the data table.
- `DataTablePaginationState`: A type that holds the pagination state of the data table.
- `useDataTable`: A hook to initialize and configure the data table.
You also import the `Heading` component to show a heading above the data table.
Next, you'll define the table's columns. Add the following before the `BrandsPage` component:
```tsx title="src/admin/routes/brands/page.tsx"
const columnHelper = createDataTableColumnHelper<Brand>()
const columns = [
columnHelper.accessor("id", {
header: "ID",
}),
columnHelper.accessor("name", {
header: "Name",
})
]
```
You use the `createDataTableColumnHelper` utility to create columns for the data table. You define two columns for the ID and name of the brands.
Then, replace the `// TODO retrieve brands` in the component with the following:
export const queryHighlights = [
["1", "currentPage", "A zero-based index of the current page of items."],
["2", "limit", "The maximum number of items per page."],
["3", "offset", "The number of items to skip before retrieving the page's items."],
["7", "useQuery", "Retrieve brands using Tanstack Query"],
["8", "fetch", "Send a request to a custom API route."],
["8", "`/admin/brands`", "The API route's path."],
["9", "query", "Query parameters to pass in the request"]
["1", "limit", "The maximum number of items per page."],
["2", "pagination", "Define a pagination state to be passed to the data table."],
["6", "offset", "The number of items to skip before retrieving the page's items."],
["10", "useQuery", "Retrieve brands using Tanstack Query"],
["11", "fetch", "Send a request to a custom API route."],
["11", "`/admin/brands`", "The API route's path."],
["12", "query", "Query parameters to pass in the request"]
]
```tsx title="src/admin/routes/brands/page.tsx" highlights={queryHighlights}
const [currentPage, setCurrentPage] = useState(0)
const limit = 15
const [pagination, setPagination] = useState<DataTablePaginationState>({
pageSize: limit,
pageIndex: 0,
})
const offset = useMemo(() => {
return currentPage * limit
}, [currentPage])
return pagination.pageIndex * limit
}, [pagination])
const { data } = useQuery<BrandsResponse>({
const { data, isLoading } = useQuery<BrandsResponse>({
queryFn: () => sdk.client.fetch(`/admin/brands`, {
query: {
limit,
@@ -400,13 +323,16 @@ const { data } = useQuery<BrandsResponse>({
}),
queryKey: [["brands", limit, offset]],
})
// TODO configure data table
```
You first define pagination-related variables:
To enable pagination in the `DataTable` component, you need to define a state variable of type `DataTablePaginationState`. It's an object having the following properties:
- `currentPage`: A zero-based index of the current page of items.
- `limit`: The maximum number of items per page.
- `offset`: The number of items to skip before retrieving the page's items. This is calculated from the `currentPage` and `limit` variables.
- `pageSize`: The maximum number of items per page. You set it to `15`.
- `pageIndex`: A zero-based index of the current page of items.
You also define a memoized `offset` value that indicates the number of items to skip before retrieving the current page's items.
Then, you use `useQuery` from [Tanstack (React) Query](https://tanstack.com/query/latest) to query the Medusa server. Tanstack Query provides features like asynchronous state management and optimized caching.
@@ -422,35 +348,46 @@ This sends a request to the [Get Brands API route](#1-get-brands-api-route), pas
### Display Brands Table
Finally, you'll display the brands in a table using the component you created earlier. Import the component at the top of `src/admin/routes/brands/page.tsx`:
Finally, you'll display the brands in a data table. Replace the `// TODO configure data table` in the component with the following:
```tsx title="src/admin/routes/brands/page.tsx"
import { Table } from "../../components/table"
const table = useDataTable({
columns,
data: data?.brands || [],
getRowId: (row) => row.id,
rowCount: data?.count || 0,
isLoading,
pagination: {
state: pagination,
onPaginationChange: setPagination,
},
})
```
You use the `useDataTable` hook to initialize and configure the data table. It accepts an object with the following properties:
- `columns`: The columns of the data table. You created them using the `createDataTableColumnHelper` utility.
- `data`: The brands to display in the table.
- `getRowId`: A function that returns a unique identifier for a row.
- `rowCount`: The total count of items. This is used to determine the number of pages.
- `isLoading`: A boolean indicating whether the data is loading.
- `pagination`: An object to configure pagination. It accepts the following properties:
- `state`: The pagination state of the data table.
- `onPaginationChange`: A function to update the pagination state.
Then, replace the `{/* TODO show brands */}` in the return statement with the following:
```tsx title="src/admin/routes/brands/page.tsx"
<Table
columns={[
{
key: "id",
label: "#",
},
{
key: "name",
label: "Name",
},
]}
data={data?.brands || []}
pageSize={data?.limit || limit}
count={data?.count || 0}
currentPage={currentPage}
setCurrentPage={setCurrentPage}
/>
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Brands</Heading>
</DataTable.Toolbar>
<DataTable.Table />
<DataTable.Pagination />
</DataTable>
```
This renders a table that shows the ID and name of the brands.
This renders the data table that shows the brands with pagination. The `DataTable` component accepts the `instance` prop, which is the object returned by the `useDataTable` hook.
---

View File

@@ -88,7 +88,7 @@ export const generatedEditDates = {
"app/learn/customization/extend-features/extend-create-product/page.mdx": "2025-01-06T11:18:58.250Z",
"app/learn/customization/custom-features/page.mdx": "2024-12-09T10:46:28.593Z",
"app/learn/customization/customize-admin/page.mdx": "2024-12-09T11:02:38.801Z",
"app/learn/customization/customize-admin/route/page.mdx": "2024-12-24T15:08:46.095Z",
"app/learn/customization/customize-admin/route/page.mdx": "2025-01-22T16:23:31.772Z",
"app/learn/customization/customize-admin/widget/page.mdx": "2024-12-09T11:02:39.108Z",
"app/learn/customization/extend-features/define-link/page.mdx": "2024-12-09T11:02:39.346Z",
"app/learn/customization/extend-features/page.mdx": "2024-12-09T11:02:39.244Z",

View File

@@ -0,0 +1,481 @@
---
sidebar_label: "Data Table"
---
import { TypeList } from "docs-ui"
export const metadata = {
title: `Data Table - Admin Components`,
}
# {metadata.title}
<Note>
This component is available after [Medusa v2.4.0+](https://github.com/medusajs/medusa/releases/tag/v2.4.0).
</Note>
The [DataTable component in Medusa UI](!ui!/components/data-table) allows you to display data in a table with sorting, filtering, and pagination.
You can use this component in your Admin Extensions to display data in a table format, especially if they're retrieved from API routes of the Medusa application.
<Note>
Refer to the [Medusa UI documentation](!ui!/components/data-table) for detailed information about the DataTable component and its different usages.
</Note>
## Example: DataTable with Data Fetching
In this example, you'll create a UI widget that shows the list of products retrieved from the [List Products API Route](!api!/admin#products_getproducts) in a data table with pagination, filtering, searching, and sorting.
Start by initializing the columns in the data table. To do that, use the `createDataTableColumnHelper` from Medusa UI:
```tsx title="src/admin/routes/custom/page.tsx"
import {
createDataTableColumnHelper,
} from "@medusajs/ui"
import {
HttpTypes,
} from "@medusajs/framework/types"
const columnHelper = createDataTableColumnHelper<HttpTypes.AdminProduct>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
// Enables sorting for the column.
enableSorting: true,
// If omitted, the header will be used instead if it's a string,
// otherwise the accessor key (id) will be used.
sortLabel: "Title",
// If omitted the default value will be "A-Z"
sortAscLabel: "A-Z",
// If omitted the default value will be "Z-A"
sortDescLabel: "Z-A",
}),
columnHelper.accessor("status", {
header: "Status",
cell: ({ getValue }) => {
const status = getValue()
return (
<Badge color={status === "published" ? "green" : "grey"} size="xsmall">
{status === "published" ? "Published" : "Draft"}
</Badge>
)
},
}),
]
```
`createDataTableColumnHelper` utility creates a column helper that helps you define the columns for the data table. The column helper has an `accessor` method that accepts two parameters:
1. The column's key in the table's data.
2. An object with the following properties:
- `header`: The column's header.
- `cell`: (optional) By default, a data's value for a column is displayed as a string. Use this property to specify custom rendering of the value. It accepts a function that returns a string or a React node. The function receives an object that has a `getValue` property function to retrieve the raw value of the cell.
- `enableSorting`: (optional) A boolean that enables sorting data by this column.
- `sortLabel`: (optional) The label for the sorting button. If omitted, the `header` will be used instead if it's a string, otherwise the accessor key (id) will be used.
- `sortAscLabel`: (optional) The label for the ascending sorting button. If omitted, the default value will be "A-Z".
- `sortDescLabel`: (optional) The label for the descending sorting button. If omitted, the default value will be "Z-A".
Next, you'll define the filters that can be applied to the data table. You'll configure filtering by product status.
To define the filters, add the following:
```tsx title="src/admin/routes/custom/page.tsx"
// other imports...
import {
// ...
createDataTableFilterHelper,
} from "@medusajs/ui"
const filterHelper = createDataTableFilterHelper<HttpTypes.AdminProduct>()
const filters = [
filterHelper.accessor("status", {
type: "select",
label: "Status",
options: [
{
label: "Published",
value: "published",
},
{
label: "Draft",
value: "draft",
},
],
}),
]
```
`createDataTableFilterHelper` utility creates a filter helper that helps you define the filters for the data table. The filter helper has an `accessor` method that accepts two parameters:
1. The key of a column in the table's data.
2. An object with the following properties:
- `type`: The type of filter. It can be either:
- `select`: A select dropdown allowing users to choose multiple values.
- `radio`: A radio button allowing users to choose one value.
- `date`: A date picker allowing users to choose a date.
- `label`: The filter's label.
- `options`: An array of objects with `label` and `value` properties. The `label` is the option's label, and the `value` is the value to filter by.
You'll now start creating the UI widget's component. Start by adding the necessary state variables:
```tsx title="src/admin/routes/custom/page.tsx"
// other imports...
import {
// ...
DataTablePaginationState,
DataTableFilteringState,
DataTableSortingState,
} from "@medusajs/ui"
import { useMemo, useState } from "react"
// ...
const limit = 15
const CustomPage = () => {
const [pagination, setPagination] = useState<DataTablePaginationState>({
pageSize: limit,
pageIndex: 0,
})
const [search, setSearch] = useState<string>("")
const [filtering, setFiltering] = useState<DataTableFilteringState>({})
const [sorting, setSorting] = useState<DataTableSortingState | null>(null)
const offset = useMemo(() => {
return pagination.pageIndex * limit
}, [pagination])
const statusFilters = useMemo(() => {
return (filtering.status || []) as ProductStatus
}, [filtering])
// TODO add data fetching logic
}
```
In the component, you've added the following state variables:
- `pagination`: An object of type `DataTablePaginationState` that holds the pagination state. It has two properties:
- `pageSize`: The number of items to show per page.
- `pageIndex`: The current page index.
- `search`: A string that holds the search query.
- `filtering`: An object of type `DataTableFilteringState` that holds the filtering state.
- `sorting`: An object of type `DataTableSortingState` that holds the sorting state.
You've also added two memoized variables:
- `offset`: How many items to skip when fetching data based on the current page.
- `statusFilters`: The selected status filters, if any.
Next, you'll fetch the products from the Medusa application. Assuming you have the JS SDK configured as explained in [this guide](../../../js-sdk/page.mdx), add the following imports at the top of the file:
```tsx title="src/admin/routes/custom/page.tsx"
import { sdk } from "../../lib/config"
import { useQuery } from "@tanstack/react-query"
```
This imports the JS SDK instance and `useQuery` from [Tanstack Query](https://tanstack.com/query/latest).
Then, replace the `TODO` in the component with the following:
```tsx title="src/admin/routes/custom/page.tsx"
const { data, isLoading } = useQuery({
queryFn: () => sdk.admin.product.list({
limit,
offset,
q: search,
status: statusFilters,
order: sorting ? `${sorting.desc ? "-" : ""}${sorting.id}` : undefined,
}),
queryKey: [["products", limit, offset, search, statusFilters, sorting?.id, sorting?.desc]],
})
// TODO configure data table
```
You use the `useQuery` hook to fetch the products from the Medusa application. In the `queryFn`, you call the `sdk.admin.product.list` method to fetch the products. You pass the following query parameters to the method:
- `limit`: The number of products to fetch per page.
- `offset`: The number of products to skip based on the current page.
- `q`: The search query, if set.
- `status`: The status filters, if set.
- `order`: The sorting order, if set.
So, whenever the user changes the current page, search query, status filters, or sorting, the products are fetched based on the new parameters.
Next, you'll configure the data table. Medusa UI provides a `useDataTable` hook that helps you configure the data table. Add the following imports at the top of the file:
```tsx title="src/admin/routes/custom/page.tsx"
import {
// ...
useDataTable,
} from "@medusajs/ui"
```
Then, replace the `TODO` in the component with the following:
```tsx title="src/admin/routes/custom/page.tsx"
const table = useDataTable({
columns,
data: data?.products || [],
getRowId: (row) => row.id,
rowCount: data?.count || 0,
isLoading,
pagination: {
state: pagination,
onPaginationChange: setPagination,
},
search: {
state: search,
onSearchChange: setSearch,
},
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
filters,
sorting: {
// Pass the pagination state and updater to the table instance
state: sorting,
onSortingChange: setSorting,
},
})
// TODO render component
```
The `useDataTable` hook accepts an object with the following properties:
- `columns`: The columns to display in the data table. You created this using the `createDataTableColumnHelper` utility.
- `data`: The products fetched from the Medusa application.
- `getRowId`: A function that returns the unique ID of a row.
- `rowCount`: The total number of products that can be retrieved. This is used to determine the number of pages.
- `isLoading`: A boolean that indicates if the data is being fetched.
- `pagination`: An object to configure pagination. It accepts with the following properties:
- `state`: The pagination React state variable.
- `onPaginationChange`: A function that updates the pagination state.
- `search`: An object to configure searching. It accepts the following properties:
- `state`: The search query React state variable.
- `onSearchChange`: A function that updates the search query state.
- `filtering`: An object to configure filtering. It accepts the following properties:
- `state`: The filtering React state variable.
- `onFilteringChange`: A function that updates the filtering state.
- `filters`: The filters to display in the data table. You created this using the `createDataTableFilterHelper` utility.
- `sorting`: An object to configure sorting. It accepts the following properties:
- `state`: The sorting React state variable.
- `onSortingChange`: A function that updates the sorting state.
Finally, you'll render the data table. But first, add the following imports at the top of the page:
```tsx title="src/admin/routes/custom/page.tsx"
import {
// ...
DataTable,
} from "@medusajs/ui"
import { SingleColumnLayout } from "../../layouts/single-column"
import { Container } from "../../components/container"
```
Aside from the `DataTable` component, you also import the [SingleColumnLayout](../../layouts/single-column/page.mdx) and [Container](../container/page.mdx) components implemented in other Admin Component guides. These components ensure a style consistent to other pages in the admin dashboard.
Then, replace the `TODO` in the component with the following:
```tsx title="src/admin/routes/custom/page.tsx"
return (
<SingleColumnLayout>
<Container>
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
<div className="flex gap-2">
<DataTable.FilterMenu tooltip="Filter" />
<DataTable.SortingMenu tooltip="Sort" />
<DataTable.Search placeholder="Search..." />
</div>
</DataTable.Toolbar>
<DataTable.Table />
<DataTable.Pagination />
</DataTable>
</Container>
</SingleColumnLayout>
)
```
You render the `DataTable` component and pass the `table` instance as a prop. In the `DataTable` component, you render a toolbar showing a heading, filter menu, sorting menu, and a search input. You also show pagination after the table.
Lastly, export the component and the UI widget's configuration at the end of the file:
```tsx title="src/admin/routes/custom/page.tsx"
// other imports...
import { defineRouteConfig } from "@medusajs/admin-sdk"
import { ChatBubbleLeftRight } from "@medusajs/icons"
// ...
export const config = defineRouteConfig({
label: "Custom",
icon: ChatBubbleLeftRight,
})
export default CustomPage
```
If you start your Medusa application and go to `localhost:9000/app/custom`, you'll see the data table showing the list of products with pagination, filtering, searching, and sorting functionalities.
### Full Example Code
```tsx title="src/admin/routes/custom/page.tsx"
import { defineRouteConfig } from "@medusajs/admin-sdk"
import { ChatBubbleLeftRight } from "@medusajs/icons"
import {
Badge,
createDataTableColumnHelper,
createDataTableFilterHelper,
DataTable,
DataTableFilteringState,
DataTablePaginationState,
DataTableSortingState,
Heading,
useDataTable,
} from "@medusajs/ui"
import { useQuery } from "@tanstack/react-query"
import { SingleColumnLayout } from "../../layouts/single-column"
import { sdk } from "../../lib/config"
import { useMemo, useState } from "react"
import { Container } from "../../components/container"
import { HttpTypes, ProductStatus } from "@medusajs/framework/types"
const columnHelper = createDataTableColumnHelper<HttpTypes.AdminProduct>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
// Enables sorting for the column.
enableSorting: true,
// If omitted, the header will be used instead if it's a string,
// otherwise the accessor key (id) will be used.
sortLabel: "Title",
// If omitted the default value will be "A-Z"
sortAscLabel: "A-Z",
// If omitted the default value will be "Z-A"
sortDescLabel: "Z-A",
}),
columnHelper.accessor("status", {
header: "Status",
cell: ({ getValue }) => {
const status = getValue()
return (
<Badge color={status === "published" ? "green" : "grey"} size="xsmall">
{status === "published" ? "Published" : "Draft"}
</Badge>
)
},
}),
]
const filterHelper = createDataTableFilterHelper<HttpTypes.AdminProduct>()
const filters = [
filterHelper.accessor("status", {
type: "select",
label: "Status",
options: [
{
label: "Published",
value: "published",
},
{
label: "Draft",
value: "draft",
},
],
}),
]
const limit = 15
const CustomPage = () => {
const [pagination, setPagination] = useState<DataTablePaginationState>({
pageSize: limit,
pageIndex: 0,
})
const [search, setSearch] = useState<string>("")
const [filtering, setFiltering] = useState<DataTableFilteringState>({})
const [sorting, setSorting] = useState<DataTableSortingState | null>(null)
const offset = useMemo(() => {
return pagination.pageIndex * limit
}, [pagination])
const statusFilters = useMemo(() => {
return (filtering.status || []) as ProductStatus
}, [filtering])
const { data, isLoading } = useQuery({
queryFn: () => sdk.admin.product.list({
limit,
offset,
q: search,
status: statusFilters,
order: sorting ? `${sorting.desc ? "-" : ""}${sorting.id}` : undefined,
}),
queryKey: [["products", limit, offset, search, statusFilters, sorting?.id, sorting?.desc]],
})
const table = useDataTable({
columns,
data: data?.products || [],
getRowId: (row) => row.id,
rowCount: data?.count || 0,
isLoading,
pagination: {
state: pagination,
onPaginationChange: setPagination,
},
search: {
state: search,
onSearchChange: setSearch,
},
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
filters,
sorting: {
// Pass the pagination state and updater to the table instance
state: sorting,
onSortingChange: setSorting,
},
})
return (
<SingleColumnLayout>
<Container>
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
<div className="flex gap-2">
<DataTable.FilterMenu tooltip="Filter" />
<DataTable.SortingMenu tooltip="Sort" />
<DataTable.Search placeholder="Search..." />
</div>
</DataTable.Toolbar>
<DataTable.Table />
<DataTable.Pagination />
</DataTable>
</Container>
</SingleColumnLayout>
)
}
export const config = defineRouteConfig({
label: "Custom",
icon: ChatBubbleLeftRight,
})
export default CustomPage
```

View File

@@ -10,6 +10,12 @@ export const metadata = {
# {metadata.title}
<Note>
If you're using [Medusa v2.4.0+](https://github.com/medusajs/medusa/releases/tag/v2.4.0), it's recommended to use the [Data Table](../data-table/page.mdx) component instead.
</Note>
The listing pages in the Admin show a table with pagination.
![Example of a table in the product listing page](https://res.cloudinary.com/dza7lstvk/image/upload/v1728295658/Medusa%20Resources/list_ddt9zc.png)

View File

@@ -2125,7 +2125,7 @@ export const generatedEditDates = {
"app/admin-components/components/header/page.mdx": "2024-10-07T11:16:47.407Z",
"app/admin-components/components/json-view-section/page.mdx": "2024-10-07T11:15:58.833Z",
"app/admin-components/components/section-row/page.mdx": "2024-10-07T11:15:58.832Z",
"app/admin-components/components/table/page.mdx": "2024-12-16T15:28:59.428Z",
"app/admin-components/components/table/page.mdx": "2025-01-22T16:00:56.772Z",
"app/admin-components/page.mdx": "2024-10-07T11:09:49.493Z",
"app/admin-components/layouts/single-column/page.mdx": "2024-10-07T11:16:06.435Z",
"app/admin-components/layouts/two-column/page.mdx": "2024-10-07T11:16:10.092Z",
@@ -5886,5 +5886,6 @@ export const generatedEditDates = {
"references/core_flows/interfaces/core_flows.ValidateProductInputStepInput/page.mdx": "2025-01-17T16:43:26.173Z",
"references/core_flows/types/core_flows.ThrowUnlessPaymentCollectionNotePaidInput/page.mdx": "2025-01-17T16:43:25.819Z",
"references/core_flows/types/core_flows.ValidatePaymentsRefundStepInput/page.mdx": "2025-01-17T16:43:26.128Z",
"references/core_flows/types/core_flows.ValidateRefundStepInput/page.mdx": "2025-01-17T16:43:26.124Z"
"references/core_flows/types/core_flows.ValidateRefundStepInput/page.mdx": "2025-01-17T16:43:26.124Z",
"app/admin-components/components/data-table/page.mdx": "2025-01-22T16:01:01.279Z"
}

View File

@@ -7,6 +7,10 @@ export const filesMap = [
"filePath": "/www/apps/resources/app/admin-components/components/container/page.mdx",
"pathname": "/admin-components/components/container"
},
{
"filePath": "/www/apps/resources/app/admin-components/components/data-table/page.mdx",
"pathname": "/admin-components/components/data-table"
},
{
"filePath": "/www/apps/resources/app/admin-components/components/forms/page.mdx",
"pathname": "/admin-components/components/forms"

View File

@@ -17377,6 +17377,15 @@ export const generatedSidebar = [
"description": "",
"children": []
},
{
"loaded": true,
"isPathHref": true,
"type": "link",
"path": "/admin-components/components/data-table",
"title": "Data Table",
"description": "",
"children": []
},
{
"loaded": true,
"isPathHref": true,

View File

@@ -16,9 +16,9 @@
"dependencies": {
"@faker-js/faker": "^8.0.2",
"@mdx-js/react": "^3.1.0",
"@medusajs/icons": "~2.0.0",
"@medusajs/ui": "~4.0.0",
"@medusajs/ui-preset": "~1.1.3",
"@medusajs/icons": "~2.4.0",
"@medusajs/ui": "~4.0.4",
"@medusajs/ui-preset": "~2.4.0",
"autoprefixer": "10.4.14",
"clsx": "^2.0.0",
"contentlayer": "^0.3.4",

View File

@@ -10,11 +10,13 @@ import { ExampleRegistry } from "@/registries/example-registry"
interface ComponentExampleProps extends React.HTMLAttributes<HTMLDivElement> {
name: string
disableCenterAlignPreview?: boolean
}
export function ComponentExample({
children,
name,
disableCenterAlignPreview = false,
...props
}: ComponentExampleProps) {
const Preview = React.useMemo(() => {
@@ -45,7 +47,8 @@ export function ComponentExample({
<div
className={clx(
"bg-medusa-bg-base border-medusa-border-base flex max-h-[400px] min-h-[400px]",
"w-full items-center justify-center overflow-auto rounded-md border px-10 py-5"
"w-full overflow-auto justify-center rounded-md border px-10 py-5",
!disableCenterAlignPreview && "items-center"
)}
>
<React.Suspense

View File

@@ -151,6 +151,13 @@ export const docsConfig: DocsConfig = {
isPathHref: true,
loaded: true,
},
{
type: "link",
title: "Data Table",
path: "/components/data-table",
isPathHref: true,
loaded: true,
},
{
type: "link",
title: "Date Picker",

View File

@@ -0,0 +1,883 @@
---
title: "DataTable"
description: "A Table component with advanced functionalities like pagination, filtering, and more."
---
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.
<Note>
This component is available after Medusa UI v4.0.4 (or Medusa v2.4.0). It is built on top of the [Table](./table.mdx) component. If you want a table with more control over its styling and functionality, use that component instead.
</Note>
## Simple Example
---
<ComponentExample name="data-table-demo" disableCenterAlignPreview />
## Usage
---
You import the `DataTable` component from `@medusajs/ui`.
```tsx
import {
DataTable,
} from "@medusajs/ui"
```
### Columns Preparation
Before using the `DataTable` component, you need to prepare its columns using the `createDataTableColumnHelper` utility:
```tsx
import {
// ...
createDataTableColumnHelper,
} from "@medusajs/ui"
const data = [
{
id: "1",
title: "Shirt",
price: 10
},
// other data...
]
const columnHelper = createDataTableColumnHelper<typeof data[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
}),
]
```
The `createDataTableColumnHelper` utility is a function that returns a helper used to generates column configurations for the `DataTable` component.
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:
- `header`: The table header text for the column.
- `enableSorting`: (optional) A boolean that indicates whether data in the table can be sorted by this column. More on sorting in [this section](#datatable-with-sorting).
### Create Table Instance
The `DataTable` component expects a table instance created using the `useDataTable` hook. Import that hook from `@medusajs/ui`:
```tsx
import {
// ...
useDataTable,
} from "@medusajs/ui"
```
Then, inside the component that will render `DataTable`, create a table instance using the `useDataTable` hook:
```tsx
export default function ProductTable () {
const table = useDataTable({
columns,
data,
getRowId: (product) => product.id,
rowCount: data.length,
isLoading: false,
})
}
```
The `useDataTable` hook accepts an object with the following properties:
- `columns`: An array of column configurations generated using the `createDataTableColumnHelper` utility.
- `data`: The data to be displayed in the table.
- `getRowId`: A function that returns the unique identifier of a row. The identifier must be a string.
- `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.
- `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.
### Render DataTable
Finally, render the `DataTable` component with the table instance created using the `useDataTable` hook:
```tsx
export default function ProductTable () {
// ...
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
}
```
In the `DataTable` component, you pass the following child components:
1. `DataTable.Toolbar`: The toolbar component shown at the top of the table. You can also add buttons for custom actions.
2. `DataTable.Table`: The table component that renders the data.
Refer to the examples later on this page to learn how to add pagination, filtering, and other functionalities using the `DataTable` component.
## API Reference
---
<ComponentReference mainComponent="DataTable" componentsToShow={[
"DataTable",
"DataTable.Table",
"DataTable.Pagination",
"DataTable.FilterMenu",
"DataTable.Search",
"DataTable.CommandBar",
"DataTable.SortingMenu",
]} />
## Example with Data Fetching
---
Refer to [this Admin Components guide](https://docs.medusajs.com/resources/admin-components/components/data-table) for an example on using the `DataTable` component with data fetching from the Medusa application.
## Configure Cell Rendering
---
<ComponentExample name="data-table-custom-cell" disableCenterAlignPreview />
The `accessor` method of the `createDataTableColumnHelper` utility accepts a `cell` property that you can use to customize the rendering of the cell content.
For example:
```tsx
const products = [
{
id: "1",
title: "Shirt",
price: 10,
is_active: true
},
{
id: "2",
title: "Pants",
price: 20,
is_active: true
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("is_active", {
header: "Status",
cell: ({ getValue }) => {
const isActive = getValue()
return (
<Badge color={isActive ? "green" : "grey"}>
{isActive ? "Active" : "Inactive"}
</Badge>
)
}
}),
// ...
]
```
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.
## DataTable with Search
---
<ComponentExample name="data-table-search" disableCenterAlignPreview />
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:
```tsx
// `useState` imported from `React`
const [search, setSearch] = useState("")
const table = useDataTable({
// ...
search: {
state: search,
onSearchChange: setSearch
}
})
```
`search` accepts the following properties:
- `state`: The search query string. This must be a React state variable, as its value will be used for the table's search input.
- `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.
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.
For example, when using a simple array as in the example above, this is how you filter the data by the search query:
```tsx
const [search, setSearch] = useState<string>("")
const shownProducts = useMemo(() => {
return products.filter((product) => product.title.toLowerCase().includes(search.toLowerCase()))
}, [search])
const table = useDataTable({
columns,
data: shownProducts,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
// Pass the state and onSearchChange to the table instance.
search: {
state: search,
onSearchChange: setSearch
}
})
```
Then, render the `DataTable.Search` component as part of the `DataTable`'s children:
```tsx
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
{/* This component renders the search bar */}
<DataTable.Search placeholder="Search..." />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
```
This will show a search input at the top of the table, in the data table's toolbar.
## DataTable with Pagination
---
<ComponentExample name="data-table-pagination" disableCenterAlignPreview />
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.
First, import the `DataTablePaginationState` type from `@medusajs/ui`:
```tsx
import {
// ...
DataTablePaginationState,
} from "@medusajs/ui"
```
Then, create a state variable to manage the pagination:
```tsx
const [pagination, setPagination] = useState<DataTablePaginationState>({
pageSize: 15,
pageIndex: 0,
})
```
The pagination state variable of type `DataTablePaginationState` is an object with the following properties:
- `pageSize`: The number of rows to display per page.
- `pageIndex`: The current page index. It's zero-based, meaning the first page would be `0`.
Next, pass the pagination object to the `useDataTable` hook:
```tsx
const table = useDataTable({
// ...
pagination: {
state: pagination,
onPaginationChange: setPagination,
},
})
```
`pagination` accepts the following properties:
- `state`: The pagination state object. This must be a React state variable of type `DataTablePaginationState`.
- `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.
You must also implement the pagination logic, such as fetching data from the Medusa application with the pagination parameters.
For example, when using a simple array as in the example above, this is how you paginate the data:
```tsx
const [pagination, setPagination] = useState<DataTablePaginationState>({
pageSize: PAGE_SIZE,
pageIndex: 0,
})
const shownProducts = useMemo(() => {
return products.slice(
pagination.pageIndex * pagination.pageSize,
(pagination.pageIndex + 1) * pagination.pageSize
)
}, [pagination])
const table = useDataTable({
data: shownProducts,
columns,
rowCount: products.length,
getRowId: (product) => product.id,
pagination: {
// Pass the pagination state and updater to the table instance
state: pagination,
onPaginationChange: setPagination,
},
isLoading: false,
});
```
Finally, render the `DataTable.Pagination` component as part of the `DataTable`'s children:
```tsx
return (
<DataTable instance={table}>
<DataTable.Toolbar>
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
{/** This component will render the pagination controls **/}
<DataTable.Pagination />
</DataTable>
)
```
This will show the pagination controls at the end of the table.
## DataTable with Filters
---
<ComponentExample name="data-table-filters" disableCenterAlignPreview />
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.
First, add the following imports from the `@medusajs/ui` package:
```tsx
import {
// ...
createDataTableFilterHelper,
DataTableFilteringState,
} from "@medusajs/ui"
```
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.
Then, create the filters using the `createDataTableFilterHelper` utility:
<Note title="Tip">
Create the filters outside the component rendering the `DataTable` component.
</Note>
```tsx
const filterHelper = createDataTableFilterHelper<typeof products[0]>()
const filters = [
filterHelper.accessor("title", {
type: "select",
label: "Title",
options: products.map((product) => ({
label: product.title,
value: product.title.toLowerCase()
}))
}),
]
```
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:
- `type`: The type of filter. It can be either:
- `select`: A select dropdown filter.
- `radio`: A radio button filter.
- `date`: A date filter.
- `label`: The label text for the filter.
- `options`: If the filter type is `select` or `radio`, an array of dropdown options. Each option has a `label` and `value` property.
<Note>
Refer to [this section](#filtering-date-values) to learn how to use date filters.
</Note>
Next, in the component rendering the `DataTable` component, create a state variable to manage the filtering, and pass the filters to the `useDataTable` hook:
```tsx
const [filtering, setFiltering] = useState<DataTableFilteringState>({})
const table = useDataTable({
// ...
filters,
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
})
```
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).
The `useDataTable` hook accepts the following properties for filtering:
- `filters`: An array of filter configurations generated using the `createDataTableFilterHelper` utility.
- `filtering`: An object with the following properties:
- `state`: The filtering state object. This must be a React state variable of type `DataTableFilteringState`.
- `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.
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.
For example, when using a simple array as in the example above, this is how you filter the data based on the filter conditions:
```tsx
const [filtering, setFiltering] = useState<DataTableFilteringState>({})
const shownProducts = useMemo(() => {
return products.filter((product) => {
return Object.entries(filtering).every(([key, value]) => {
if (!value) {
return true
}
if (typeof value === "string") {
// @ts-ignore
return product[key].toString().toLowerCase().includes(value.toString().toLowerCase())
}
if (Array.isArray(value)) {
// @ts-ignore
return value.includes(product[key].toLowerCase())
}
if (typeof value === "object") {
// @ts-ignore
const date = new Date(product[key])
let matching = false
if ("$gte" in value && value.$gte) {
matching = date >= new Date(value.$gte as number)
}
if ("$lte" in value && value.$lte) {
matching = date <= new Date(value.$lte as number)
}
if ("$lt" in value && value.$lt) {
matching = date < new Date(value.$lt as number)
}
if ("$gt" in value && value.$gt) {
matching = date > new Date(value.$gt as number)
}
return matching
}
})
})
}, [filtering])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
filters
})
```
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:
- `undefined` if the user is still selecting the value.
- A string if the filter type is `radio`, as the user can choose only one value.
- An array of strings if the filter type is `select`, as the user can choose multiple values.
- 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).
Finally, render the `DataTable.FilterMenu` component as part of the `DataTable`'s children:
```tsx
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which filters to apply to the table data. **/}
<DataTable.FilterMenu tooltip="Filter" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
```
This will show a filter menu at the top of the table, in the data table's toolbar.
### Filtering Date Values
<ComponentExample name="data-table-filters-date" disableCenterAlignPreview />
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:
```tsx
const filters = [
// ...
filterHelper.accessor("created_at", {
type: "date",
label: "Created At",
format: "date",
formatDateValue: (date) => date.toLocaleString(),
rangeOptionStartLabel: "From",
rangeOptionEndLabel: "To",
rangeOptionLabel: "Between",
options: [
{
label: "Today",
value: {
$gte: new Date(new Date().setHours(0, 0, 0, 0)).toString(),
$lte: new Date(new Date().setHours(23, 59, 59, 999)).toString()
}
},
{
label: "Yesterday",
value: {
$gte: new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000).toString(),
$lte: new Date(new Date().setHours(0, 0, 0, 0)).toString()
}
},
{
label: "Last Week",
value: {
$gte: new Date(new Date().setHours(0, 0, 0, 0) - 7 * 24 * 60 * 60 * 1000).toString(),
$lte: new Date(new Date().setHours(0, 0, 0, 0)).toString()
},
},
]
}),
]
```
When the filter type is `date`, the filter configuration object passed as a second parameter to the `accessor` method accepts the following properties:
- `format`: The format of the date value. It can be either `date` to filter by dates, or `datetime` to filter by dates and times.
- `formatDateValue`: A function that formats the date value when displaying it in the filter options.
- `rangeOptionStartLabel`: (optional) The label for the start date input in the range filter.
- `rangeOptionEndLabel`: (optional) The label for the end date input in the range filter.
- `rangeOptionLabel`: (optional) The label for the range filter option.
- `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:
- `$gt`: Greater than.
- `$lt`: Less than.
- `$lte`: Less than or equal to.
- `$gte`: Greater than or equal to.
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.
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:
```tsx
const shownProducts = useMemo(() => {
return products.filter((product) => {
return Object.entries(filtering).every(([key, value]) => {
if (!value) {
return true
}
// other types checks...
if (typeof value === "object") {
// @ts-ignore
const date = new Date(product[key])
let matching = false
if ("$gte" in value && value.$gte) {
matching = date >= new Date(value.$gte as number)
}
if ("$lte" in value && value.$lte) {
matching = date <= new Date(value.$lte as number)
}
if ("$lt" in value && value.$lt) {
matching = date < new Date(value.$lt as number)
}
if ("$gt" in value && value.$gt) {
matching = date > new Date(value.$gt as number)
}
return matching
}
})
})
}, [filtering])
```
### Initial Filter Values
<ComponentExample name="data-table-filters-initial" disableCenterAlignPreview />
If you want to set initial filter values, you can set the initial state of the `filtering` state variable:
```tsx
const [filtering, setFiltering] = useState<DataTableFilteringState>({
title: ["shirt"]
})
```
The user can still change the filter values, but the initial values will be applied when the table is first rendered.
## DataTable with Sorting
---
<ComponentExample name="data-table-sorting" disableCenterAlignPreview />
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.
First, in the `columns` array created by the columns helper, specify for the sortable columns the following properties:
```tsx
const columns = [
columnHelper.accessor("title", {
header: "Title",
// Enables sorting for the column.
enableSorting: true,
// If omitted, the header will be used instead if it's a string,
// otherwise the accessor key (id) will be used.
sortLabel: "Title",
// If omitted the default value will be "A-Z"
sortAscLabel: "A-Z",
// If omitted the default value will be "Z-A"
sortDescLabel: "Z-A",
}),
]
```
The `accessor` method of the helper function accepts the following properties for sorting:
- `enableSorting`: A boolean that indicates whether data in the table can be sorted by this column.
- `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.
- `sortAscLabel`: The label text for the ascending sort button. If omitted, the default value will be `A-Z`.
- `sortDescLabel`: The label text for the descending sort button. If omitted, the default value will be `Z-A`.
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:
```tsx
import {
// ...
DataTableSortingState
} from "@medusajs/ui"
export default function ProductTable () {
const [sorting, setSorting] = useState<DataTableSortingState | null>(null);
const table = useDataTable({
// ...
sorting: {
state: sorting,
onSortingChange: setSorting,
},
})
// ...
}
```
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).
The `sorting` object passed to the `useDataTable` hook accepts the following properties:
- `state`: The sorting state object. This must be a React state variable of type `DataTableSortingState`.
- `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.
You must also implement the sorting logic, such as sending the sorting conditions to the Medusa application when fetching data.
For example, when using a simple array as in the example above, this is how you sort the data based on the sorting conditions:
```tsx
const [sorting, setSorting] = useState<DataTableSortingState | null>(null);
const shownProducts = useMemo(() => {
if (!sorting) {
return products
}
return products.slice().sort((a, b) => {
// @ts-ignore
const aVal = a[sorting.id]
// @ts-ignore
const bVal = b[sorting.id]
if (aVal < bVal) {
return sorting.desc ? 1 : -1
}
if (aVal > bVal) {
return sorting.desc ? -1 : 1
}
return 0
})
}, [sorting])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
sorting: {
// Pass the pagination state and updater to the table instance
state: sorting,
onSortingChange: setSorting,
},
isLoading: false,
})
```
The `sorting` state object has the following properties:
- `id`: The column key to sort by.
- `desc`: A boolean that indicates whether to sort in descending order.
Finally, render the `DataTable.SortingMenu` component as part of the `DataTable`'s children:
```tsx
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}
<DataTable.SortingMenu tooltip="Sort" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
```
This will show a sorting menu at the top of the table, in the data table's toolbar.
### Initial Sort Values
<ComponentExample name="data-table-sorting-initial" disableCenterAlignPreview />
If you want to set initial sort values, you can set the initial state of the `sorting` state variable:
```tsx
const [sorting, setSorting] = useState<DataTableSortingState | null>({
id: "title",
desc: false,
})
```
The user can still change the sort values, but the initial values will be applied when the table is first rendered.
## DataTable with Command Bar
---
<ComponentExample name="data-table-commands" disableCenterAlignPreview />
The object passed to the `useDataTable` hook accepts a `commands` object property that you can use to add custom actions to the `DataTable` component.
First, add the following imports from `@medusajs/ui`:
```tsx
import {
// ...
createDataTableCommandHelper,
DataTableRowSelectionState,
} from "@medusajs/ui"
```
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.
Then, in the `columns` array created by the columns helper, add a `select` column:
```tsx
const columns = [
// Commands requires a select column.
columnHelper.select(),
// ...
]
```
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.
Next, create the commands using the `createDataTableCommandHelper` utility:
<Note title="Tip">
Create the commands outside the component rendering the `DataTable` component.
</Note>
```tsx
const commandHelper = createDataTableCommandHelper()
const useCommands = () => {
return [
commandHelper.command({
label: "Delete",
shortcut: "D",
action: async (selection) => {
const productsToDeleteIds = Object.keys(selection)
// TODO remove products from the server
}
})
]
}
```
The `createDataTableCommandHelper` utility is a function that returns a helper function to generate command configurations for the `DataTable` component.
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.
The `command` method of the helper function accepts the following properties:
- `label`: The label text for the command.
- `shortcut`: The keyboard shortcut for the command. This shortcut only works when rows are selected in the table.
- `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.
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:
```tsx
const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>({})
const commands = useCommands()
const instance = useDataTable({
data: products,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
commands,
rowSelection: {
state: rowSelection,
onRowSelectionChange: setRowSelection,
},
})
```
You create a state variable of type `DataTableRowSelectionState` to manage the selected rows. You also retrieve the commands by calling the `useCommand` function.
The `useDataTable` hook accepts the following properties for commands:
- `commands`: An array of command configurations generated using the `createDataTableCommandHelper` utility.
- `rowSelection`: An object that enables selecting rows in the table. It accepts the following properties:
- `state`: The row selection state object. This must be a React state variable of type `DataTableRowSelectionState`.
- `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.
Finally, render the `DataTable.CommandBar` component as part of the `DataTable`'s children:
```tsx
return (
<DataTable instance={instance}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
{/** This component will the command bar when the user has selected at least one row. **/}
<DataTable.CommandBar selectedLabel={(count) => `${count} selected`} />
</DataTable>
)
```
This will show a command bar when the user has selected at least one row in the table.

View File

@@ -3,6 +3,12 @@ title: "Table"
description: "A Table component for displaying data."
---
<Note>
If you're looking to add a table in your Medusa Admin Extensions with features like pagination and filters, refer to the [DataTable](./data-table.mdx) component instead.
</Note>
<ComponentExample name="table-demo" />
## Usage

View File

@@ -0,0 +1,76 @@
import { DataTable, DataTableRowSelectionState, Heading, createDataTableColumnHelper, createDataTableCommandHelper, useDataTable } from "@medusajs/ui"
import { useState } from "react"
let products = [
{
id: "1",
title: "Shirt",
price: 10,
},
{
id: "2",
title: "Pants",
price: 20,
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
// Commands requires a select column.
columnHelper.select(),
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
]
const commandHelper = createDataTableCommandHelper()
const useCommands = () => {
return [
commandHelper.command({
label: "Delete",
shortcut: "D",
action: async (selection) => {
const productsToDeleteIds = Object.keys(selection)
alert(`You deleted product(s) with IDs: ${productsToDeleteIds.join()}`)
}
})
]
}
export default function ProductTable () {
const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>({})
const commands = useCommands()
const instance = useDataTable({
data: products,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
commands,
rowSelection: {
state: rowSelection,
onRowSelectionChange: setRowSelection,
},
});
return (
<DataTable instance={instance}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
{/** This component will the command bar when the user has selected at least one row. **/}
<DataTable.CommandBar selectedLabel={(count) => `${count} selected`} />
</DataTable>
);
};

View File

@@ -0,0 +1,59 @@
import { createDataTableColumnHelper, useDataTable, DataTable, Heading, Badge } from "@medusajs/ui"
const products = [
{
id: "1",
title: "Shirt",
price: 10,
is_active: true
},
{
id: "2",
title: "Pants",
price: 20,
is_active: false
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
columnHelper.accessor("is_active", {
header: "Status",
cell: ({ getValue }) => {
const isActive = getValue()
return (
<Badge color={isActive ? "green" : "grey"} size="xsmall">
{isActive ? "Active" : "Inactive"}
</Badge>
)
}
})
]
export default function ProductTable () {
const table = useDataTable({
columns,
data: products,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
})
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
}

View File

@@ -0,0 +1,46 @@
import { createDataTableColumnHelper, useDataTable, DataTable, Heading } from "@medusajs/ui"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
]
export default function ProductTable () {
const table = useDataTable({
columns,
data: products,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
})
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
}

View File

@@ -0,0 +1,137 @@
import { DataTable, DataTableFilteringState, Heading, createDataTableColumnHelper, createDataTableFilterHelper, useDataTable } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10,
created_at: new Date()
},
{
id: "2",
title: "Pants",
price: 20,
created_at: new Date("2026-01-01")
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
columnHelper.accessor("created_at", {
header: "Created At",
cell: ({ getValue }) => {
return getValue().toLocaleString()
}
}),
]
const filterHelper = createDataTableFilterHelper<typeof products[0]>()
const filters = [
filterHelper.accessor("created_at", {
type: "date",
label: "Created At",
format: "date",
formatDateValue: (date) => date.toLocaleString(),
rangeOptionStartLabel: "From",
rangeOptionEndLabel: "To",
rangeOptionLabel: "Between",
options: [
{
label: "Today",
value: {
$gte: new Date(new Date().setHours(0, 0, 0, 0)).toString(),
$lte: new Date(new Date().setHours(23, 59, 59, 999)).toString()
}
},
{
label: "Yesterday",
value: {
$gte: new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000).toString(),
$lte: new Date(new Date().setHours(0, 0, 0, 0)).toString()
}
},
{
label: "Last Week",
value: {
$gte: new Date(new Date().setHours(0, 0, 0, 0) - 7 * 24 * 60 * 60 * 1000).toString(),
$lte: new Date(new Date().setHours(0, 0, 0, 0)).toString()
},
},
]
}),
]
export default function ProductTable () {
const [filtering, setFiltering] = useState<DataTableFilteringState>({})
const shownProducts = useMemo(() => {
return products.filter((product) => {
return Object.entries(filtering).every(([key, value]) => {
if (!value) {
return true
}
if (typeof value === "string") {
// @ts-ignore
return product[key].toString().toLowerCase().includes(value.toString().toLowerCase())
}
if (Array.isArray(value)) {
// @ts-ignore
return value.includes(product[key].toLowerCase())
}
if (typeof value === "object") {
// @ts-ignore
const date = new Date(product[key])
let matching = false
if ("$gte" in value && value.$gte) {
matching = date >= new Date(value.$gte as number)
}
if ("$lte" in value && value.$lte) {
matching = date <= new Date(value.$lte as number)
}
if ("$lt" in value && value.$lt) {
matching = date < new Date(value.$lt as number)
}
if ("$gt" in value && value.$gt) {
matching = date > new Date(value.$gt as number)
}
return matching
}
})
})
}, [filtering])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
filters
});
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which filters to apply to the table data. **/}
<DataTable.FilterMenu tooltip="Filter" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
);
};

View File

@@ -0,0 +1,107 @@
import { DataTable, DataTableFilteringState, Heading, createDataTableColumnHelper, createDataTableFilterHelper, useDataTable } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
]
const filterHelper = createDataTableFilterHelper<typeof products[0]>()
const filters = [
filterHelper.accessor("title", {
type: "select",
label: "Title",
options: products.map((product) => ({
label: product.title,
value: product.title.toLowerCase()
}))
}),
]
export default function ProductTable () {
const [filtering, setFiltering] = useState<DataTableFilteringState>({
title: ["shirt"]
})
const shownProducts = useMemo(() => {
return products.filter((product) => {
return Object.entries(filtering).every(([key, value]) => {
if (!value) {
return true
}
if (typeof value === "string") {
// @ts-ignore
return product[key].toString().toLowerCase().includes(value.toString().toLowerCase())
}
if (Array.isArray(value)) {
// @ts-ignore
return value.includes(product[key].toLowerCase())
}
if (typeof value === "object") {
// @ts-ignore
const date = new Date(product[key])
let matching = false
if ("$gte" in value && value.$gte) {
matching = date >= new Date(value.$gte as number)
}
if ("$lte" in value && value.$lte) {
matching = date <= new Date(value.$lte as number)
}
if ("$lt" in value && value.$lt) {
matching = date < new Date(value.$lt as number)
}
if ("$gt" in value && value.$gt) {
matching = date > new Date(value.$gt as number)
}
return matching
}
})
})
}, [filtering])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
filters
});
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which filters to apply to the table data. **/}
<DataTable.FilterMenu tooltip="Filter" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
);
};

View File

@@ -0,0 +1,105 @@
import { DataTable, DataTableFilteringState, Heading, createDataTableColumnHelper, createDataTableFilterHelper, useDataTable } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
]
const filterHelper = createDataTableFilterHelper<typeof products[0]>()
const filters = [
filterHelper.accessor("title", {
type: "select",
label: "Title",
options: products.map((product) => ({
label: product.title,
value: product.title.toLowerCase()
}))
}),
]
export default function ProductTable () {
const [filtering, setFiltering] = useState<DataTableFilteringState>({})
const shownProducts = useMemo(() => {
return products.filter((product) => {
return Object.entries(filtering).every(([key, value]) => {
if (!value) {
return true
}
if (typeof value === "string") {
// @ts-ignore
return product[key].toString().toLowerCase().includes(value.toString().toLowerCase())
}
if (Array.isArray(value)) {
// @ts-ignore
return value.includes(product[key].toLowerCase())
}
if (typeof value === "object") {
// @ts-ignore
const date = new Date(product[key])
let matching = false
if ("$gte" in value && value.$gte) {
matching = date >= new Date(value.$gte as number)
}
if ("$lte" in value && value.$lte) {
matching = date <= new Date(value.$lte as number)
}
if ("$lt" in value && value.$lt) {
matching = date < new Date(value.$lt as number)
}
if ("$gt" in value && value.$gt) {
matching = date > new Date(value.$gt as number)
}
return matching
}
})
})
}, [filtering])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
filtering: {
state: filtering,
onFilteringChange: setFiltering,
},
filters
});
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which filters to apply to the table data. **/}
<DataTable.FilterMenu tooltip="Filter" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
);
};

View File

@@ -0,0 +1,143 @@
import { DataTable, Heading, createDataTableColumnHelper, useDataTable, type DataTablePaginationState } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
},
{
id: "3",
title: "Hat",
price: 15
},
{
id: "4",
title: "Socks",
price: 5
},
{
id: "5",
title: "Shoes",
price: 50
},
{
id: "6",
title: "Jacket",
price: 100
},
{
id: "7",
title: "Scarf",
price: 25
},
{
id: "8",
title: "Gloves",
price: 12
},
{
id: "9",
title: "Belt",
price: 18
},
{
id: "10",
title: "Sunglasses",
price: 30
},
{
id: "11",
title: "Watch",
price: 200
},
{
id: "12",
title: "Tie",
price: 20
},
{
id: "13",
title: "Sweater",
price: 40
},
{
id: "14",
title: "Jeans",
price: 60
},
{
id: "15",
title: "Shorts",
price: 25
},
{
id: "16",
title: "Blouse",
price: 35
},
{
id: "17",
title: "Dress",
price: 80
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
]
const PAGE_SIZE = 10;
export default function ProductTable () {
const [pagination, setPagination] = useState<DataTablePaginationState>({
pageSize: PAGE_SIZE,
pageIndex: 0,
})
const shownProducts = useMemo(() => {
return products.slice(
pagination.pageIndex * pagination.pageSize,
(pagination.pageIndex + 1) * pagination.pageSize
)
}, [pagination])
const table = useDataTable({
data: shownProducts,
columns,
rowCount: products.length,
getRowId: (product) => product.id,
pagination: {
// Pass the pagination state and updater to the table instance
state: pagination,
onPaginationChange: setPagination,
},
isLoading: false,
});
return (
<DataTable instance={table}>
<DataTable.Toolbar>
<Heading>Products</Heading>
</DataTable.Toolbar>
<DataTable.Table />
{/** This component will render the pagination controls **/}
<DataTable.Pagination />
</DataTable>
);
};

View File

@@ -0,0 +1,60 @@
import { createDataTableColumnHelper, useDataTable, DataTable, Heading } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
enableSorting: true,
}),
columnHelper.accessor("price", {
header: "Price",
enableSorting: true,
}),
]
export default function ProductTable () {
const [search, setSearch] = useState<string>("")
const shownProducts = useMemo(() => {
return products.filter((product) => product.title.toLowerCase().includes(search.toLowerCase()))
}, [search])
const table = useDataTable({
columns,
data: shownProducts,
getRowId: (product) => product.id,
rowCount: products.length,
isLoading: false,
// Pass the state and onSearchChange to the table instance.
search: {
state: search,
onSearchChange: setSearch
}
})
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
<Heading>Products</Heading>
{/* This component renders the search bar */}
<DataTable.Search placeholder="Search..." />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
)
}

View File

@@ -0,0 +1,85 @@
import { DataTable, DataTableSortingState, Heading, createDataTableColumnHelper, useDataTable } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
// Enables sorting for the column.
enableSorting: true,
// If omitted, the header will be used instead if it's a string,
// otherwise the accessor key (id) will be used.
sortLabel: "Title",
// If omitted the default value will be "A-Z"
sortAscLabel: "A-Z",
// If omitted the default value will be "Z-A"
sortDescLabel: "Z-A",
}),
columnHelper.accessor("price", {
header: "Price",
}),
]
export default function ProductTable () {
const [sorting, setSorting] = useState<DataTableSortingState | null>({
id: "title",
desc: false,
})
const shownProducts = useMemo(() => {
if (!sorting) {
return products
}
return products.slice().sort((a, b) => {
// @ts-ignore
const aVal = a[sorting.id]
// @ts-ignore
const bVal = b[sorting.id]
if (aVal < bVal) {
return sorting.desc ? 1 : -1
}
if (aVal > bVal) {
return sorting.desc ? -1 : 1
}
return 0
})
}, [sorting])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
sorting: {
// Pass the pagination state and updater to the table instance
state: sorting,
onSortingChange: setSorting,
},
isLoading: false,
})
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}
<DataTable.SortingMenu tooltip="Sort" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
);
};

View File

@@ -0,0 +1,82 @@
import { DataTable, DataTableSortingState, Heading, createDataTableColumnHelper, useDataTable } from "@medusajs/ui"
import { useMemo, useState } from "react"
const products = [
{
id: "1",
title: "Shirt",
price: 10
},
{
id: "2",
title: "Pants",
price: 20
}
]
const columnHelper = createDataTableColumnHelper<typeof products[0]>()
const columns = [
columnHelper.accessor("title", {
header: "Title",
// Enables sorting for the column.
enableSorting: true,
// If omitted, the header will be used instead if it's a string,
// otherwise the accessor key (id) will be used.
sortLabel: "Title",
// If omitted the default value will be "A-Z"
sortAscLabel: "A-Z",
// If omitted the default value will be "Z-A"
sortDescLabel: "Z-A",
}),
columnHelper.accessor("price", {
header: "Price",
}),
]
export default function ProductTable () {
const [sorting, setSorting] = useState<DataTableSortingState | null>(null);
const shownProducts = useMemo(() => {
if (!sorting) {
return products
}
return products.slice().sort((a, b) => {
// @ts-ignore
const aVal = a[sorting.id]
// @ts-ignore
const bVal = b[sorting.id]
if (aVal < bVal) {
return sorting.desc ? 1 : -1
}
if (aVal > bVal) {
return sorting.desc ? -1 : 1
}
return 0
})
}, [sorting])
const table = useDataTable({
data: shownProducts,
columns,
getRowId: (product) => product.id,
rowCount: products.length,
sorting: {
// Pass the pagination state and updater to the table instance
state: sorting,
onSortingChange: setSorting,
},
isLoading: false,
})
return (
<DataTable instance={table}>
<DataTable.Toolbar className="flex justify-between items-center">
<Heading>Products</Heading>
{/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}
<DataTable.SortingMenu tooltip="Sort" />
</DataTable.Toolbar>
<DataTable.Table />
</DataTable>
);
};

View File

@@ -83,15 +83,75 @@ export const ExampleRegistry: Record<string, ExampleType> = {
file: "src/examples/badge-large.tsx",
},
"badge-rounded-full": {
name: "badge-rounded",
name: "badge-rounded-full",
component: React.lazy(async () => import("@/examples/badge-rounded-full")),
file: "src/examples/badge-rounded-full.tsx",
},
"badge-rounded-base": {
name: "badge-rounded",
name: "badge-rounded-base",
component: React.lazy(async () => import("@/examples/badge-rounded-base")),
file: "src/examples/badge-rounded-base.tsx",
},
"data-table-demo": {
name: "data-table-demo",
component: React.lazy(async () => import("@/examples/data-table-demo")),
file: "src/examples/data-table-demo.tsx",
},
"data-table-custom-cell": {
name: "data-table-custom-cell",
component: React.lazy(
async () => import("@/examples/data-table-custom-cell")
),
file: "src/examples/data-table-custom-cell.tsx",
},
"data-table-search": {
name: "data-table-search",
component: React.lazy(async () => import("@/examples/data-table-search")),
file: "src/examples/data-table-search.tsx",
},
"data-table-pagination": {
name: "data-table-pagination",
component: React.lazy(
async () => import("@/examples/data-table-pagination")
),
file: "src/examples/data-table-pagination.tsx",
},
"data-table-filters": {
name: "data-table-filters",
component: React.lazy(async () => import("@/examples/data-table-filters")),
file: "src/examples/data-table-filters.tsx",
},
"data-table-filters-date": {
name: "data-table-filters-date",
component: React.lazy(
async () => import("@/examples/data-table-filters-date")
),
file: "src/examples/data-table-filters-date.tsx",
},
"data-table-filters-initial": {
name: "data-table-filters-initial",
component: React.lazy(
async () => import("@/examples/data-table-filters-initial")
),
file: "src/examples/data-table-filters-initial.tsx",
},
"data-table-sorting": {
name: "data-table-sorting",
component: React.lazy(async () => import("@/examples/data-table-sorting")),
file: "src/examples/data-table-sorting.tsx",
},
"data-table-sorting-initial": {
name: "data-table-sorting-initial",
component: React.lazy(
async () => import("@/examples/data-table-sorting-initial")
),
file: "src/examples/data-table-sorting-initial.tsx",
},
"data-table-commands": {
name: "data-table-commands",
component: React.lazy(async () => import("@/examples/data-table-commands")),
file: "src/examples/data-table-commands.tsx",
},
"icon-badge-demo": {
name: "icon-badge-demo",
component: React.lazy(async () => import("@/examples/icon-badge-demo")),

View File

@@ -0,0 +1,23 @@
{
"description": "",
"methods": [],
"displayName": "DataTable.ActionCell",
"props": {
"ctx": {
"required": true,
"tsType": {
"name": "CellContext",
"elements": [
{
"name": "TData"
},
{
"name": "unknown"
}
],
"raw": "CellContext<TData, unknown>"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,23 @@
{
"description": "This component adds a command bar to the data table, which is used\nto show commands that can be executed on the selected rows.",
"methods": [],
"displayName": "DataTable.CommandBar",
"props": {
"selectedLabel": {
"required": false,
"tsType": {
"name": "union",
"raw": "((count: number) => string) | string",
"elements": [
{
"name": "unknown"
},
{
"name": "string"
}
]
},
"description": "The label to show when items are selected. If a function is passed, \nit will be called with the count of selected items."
}
}
}

View File

@@ -0,0 +1,21 @@
{
"description": "",
"methods": [],
"displayName": "DataTable.Filter",
"props": {
"id": {
"required": true,
"tsType": {
"name": "string"
},
"description": ""
},
"filter": {
"required": true,
"tsType": {
"name": "unknown"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,18 @@
{
"description": "",
"methods": [],
"displayName": "DataTable.FilterBar",
"props": {
"clearAllFiltersLabel": {
"required": false,
"tsType": {
"name": "string"
},
"description": "",
"defaultValue": {
"value": "\"Clear all\"",
"computed": false
}
}
}
}

View File

@@ -0,0 +1,14 @@
{
"description": "This component adds a filter menu to the data table, allowing users\nto filter the table's data.",
"methods": [],
"displayName": "DataTable.FilterMenu",
"props": {
"tooltip": {
"required": false,
"tsType": {
"name": "string"
},
"description": "The tooltip to show when hovering over the filter menu."
}
}
}

View File

@@ -0,0 +1,15 @@
{
"description": "This component adds a pagination component and functionality to the data table.",
"methods": [],
"displayName": "DataTable.Pagination",
"props": {
"translations": {
"required": false,
"tsType": {
"name": "ReactComponentProps[\"translations\"]",
"raw": "React.ComponentProps<typeof Table.Pagination>[\"translations\"]"
},
"description": "The translations for strings in the pagination component."
}
}
}

View File

@@ -0,0 +1,28 @@
{
"description": "This component adds a search input to the data table, allowing users\nto search through the table's data.",
"methods": [],
"displayName": "DataTable.Search",
"props": {
"autoFocus": {
"required": false,
"tsType": {
"name": "boolean"
},
"description": "If true, the search input will be focused on mount."
},
"className": {
"required": false,
"tsType": {
"name": "string"
},
"description": "Additional classes to pass to the search input."
},
"placeholder": {
"required": false,
"tsType": {
"name": "string"
},
"description": "The placeholder text to show in the search input."
}
}
}

View File

@@ -0,0 +1,23 @@
{
"description": "",
"methods": [],
"displayName": "DataTable.SelectCell",
"props": {
"ctx": {
"required": true,
"tsType": {
"name": "DataTableCellContext",
"elements": [
{
"name": "TData"
},
{
"name": "unknown"
}
],
"raw": "DataTableCellContext<TData, unknown>"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,24 @@
{
"description": "",
"methods": [],
"displayName": "DataTable.SortingIcon",
"props": {
"direction": {
"required": true,
"tsType": {
"name": "union",
"raw": "DataTableSortDirection | false",
"elements": [
{
"name": "DataTableSortDirection"
},
{
"name": "literal",
"value": "false"
}
]
},
"description": ""
}
}
}

View File

@@ -0,0 +1,14 @@
{
"description": "This component adds a sorting menu to the data table, allowing users\nto sort the table's data.",
"methods": [],
"displayName": "DataTable.SortingMenu",
"props": {
"tooltip": {
"required": false,
"tsType": {
"name": "string"
},
"description": "The tooltip to show when hovering over the sorting menu."
}
}
}

View File

@@ -0,0 +1,98 @@
{
"description": "This component renders the table in a data table, supporting advanced features.\nIt's useful to create tables similar to those in the Medusa Admin dashboard.",
"methods": [],
"displayName": "DataTable.Table",
"props": {
"emptyState": {
"required": false,
"tsType": {
"name": "signature",
"type": "object",
"raw": "{\n /**\n * The empty state to display when the table is filtered, but no rows are found.\n */\n filtered?: DataTableEmptyStateContent\n /**\n * The empty state to display when the table is empty.\n */\n empty?: DataTableEmptyStateContent\n}",
"signature": {
"properties": [
{
"key": "filtered",
"value": {
"name": "signature",
"type": "object",
"raw": "{\n /**\n * The heading to display in the empty state.\n */\n heading?: string\n /**\n * The description to display in the empty state.\n */\n description?: string\n /**\n * A custom component to display in the empty state, if provided it will override the heading and description.\n */\n custom?: React.ReactNode\n}",
"signature": {
"properties": [
{
"key": "heading",
"value": {
"name": "string",
"required": false
},
"description": "The heading to display in the empty state."
},
{
"key": "description",
"value": {
"name": "string",
"required": false
},
"description": "The description to display in the empty state."
},
{
"key": "custom",
"value": {
"name": "ReactReactNode",
"raw": "React.ReactNode",
"required": false
},
"description": "A custom component to display in the empty state, if provided it will override the heading and description."
}
]
},
"required": false
},
"description": "The empty state to display when the table is filtered, but no rows are found."
},
{
"key": "empty",
"value": {
"name": "signature",
"type": "object",
"raw": "{\n /**\n * The heading to display in the empty state.\n */\n heading?: string\n /**\n * The description to display in the empty state.\n */\n description?: string\n /**\n * A custom component to display in the empty state, if provided it will override the heading and description.\n */\n custom?: React.ReactNode\n}",
"signature": {
"properties": [
{
"key": "heading",
"value": {
"name": "string",
"required": false
},
"description": "The heading to display in the empty state."
},
{
"key": "description",
"value": {
"name": "string",
"required": false
},
"description": "The description to display in the empty state."
},
{
"key": "custom",
"value": {
"name": "ReactReactNode",
"raw": "React.ReactNode",
"required": false
},
"description": "A custom component to display in the empty state, if provided it will override the heading and description."
}
]
},
"required": false
},
"description": "The empty state to display when the table is empty."
}
]
}
},
"description": "The empty state to display when the table is empty."
}
}
}

View File

@@ -0,0 +1,35 @@
{
"description": "This component creates a data table with filters, pagination, sorting, and more.\nIt's built on top of the `Table` component while expanding its functionality.",
"methods": [],
"displayName": "DataTable",
"props": {
"instance": {
"required": true,
"tsType": {
"name": "UseDataTableReturn",
"elements": [
{
"name": "TData"
}
],
"raw": "UseDataTableReturn<TData>"
},
"description": "The instance returned by the `useDataTable` hook."
},
"children": {
"required": false,
"tsType": {
"name": "ReactReactNode",
"raw": "React.ReactNode"
},
"description": "The children of the component."
},
"className": {
"required": false,
"tsType": {
"name": "string"
},
"description": "Additional classes to pass to the wrapper `div` of the component."
}
}
}

View File

@@ -0,0 +1,28 @@
{
"description": "",
"methods": [],
"displayName": "DataTableContextProvider",
"props": {
"instance": {
"required": true,
"tsType": {
"name": "UseDataTableReturn",
"elements": [
{
"name": "TData"
}
],
"raw": "UseDataTableReturn<TData>"
},
"description": ""
},
"children": {
"required": true,
"tsType": {
"name": "ReactReactNode",
"raw": "React.ReactNode"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,105 @@
{
"description": "",
"methods": [],
"displayName": "DataTableEmptyStateDisplay",
"props": {
"state": {
"required": true,
"tsType": {
"name": "DataTableEmptyState"
},
"description": ""
},
"props": {
"required": false,
"tsType": {
"name": "signature",
"type": "object",
"raw": "{\n /**\n * The empty state to display when the table is filtered, but no rows are found.\n */\n filtered?: DataTableEmptyStateContent\n /**\n * The empty state to display when the table is empty.\n */\n empty?: DataTableEmptyStateContent\n}",
"signature": {
"properties": [
{
"key": "filtered",
"value": {
"name": "signature",
"type": "object",
"raw": "{\n /**\n * The heading to display in the empty state.\n */\n heading?: string\n /**\n * The description to display in the empty state.\n */\n description?: string\n /**\n * A custom component to display in the empty state, if provided it will override the heading and description.\n */\n custom?: React.ReactNode\n}",
"signature": {
"properties": [
{
"key": "heading",
"value": {
"name": "string",
"required": false
},
"description": "The heading to display in the empty state."
},
{
"key": "description",
"value": {
"name": "string",
"required": false
},
"description": "The description to display in the empty state."
},
{
"key": "custom",
"value": {
"name": "ReactReactNode",
"raw": "React.ReactNode",
"required": false
},
"description": "A custom component to display in the empty state, if provided it will override the heading and description."
}
]
},
"required": false
},
"description": "The empty state to display when the table is filtered, but no rows are found."
},
{
"key": "empty",
"value": {
"name": "signature",
"type": "object",
"raw": "{\n /**\n * The heading to display in the empty state.\n */\n heading?: string\n /**\n * The description to display in the empty state.\n */\n description?: string\n /**\n * A custom component to display in the empty state, if provided it will override the heading and description.\n */\n custom?: React.ReactNode\n}",
"signature": {
"properties": [
{
"key": "heading",
"value": {
"name": "string",
"required": false
},
"description": "The heading to display in the empty state."
},
{
"key": "description",
"value": {
"name": "string",
"required": false
},
"description": "The description to display in the empty state."
},
{
"key": "custom",
"value": {
"name": "ReactReactNode",
"raw": "React.ReactNode",
"required": false
},
"description": "A custom component to display in the empty state, if provided it will override the heading and description."
}
]
},
"required": false
},
"description": "The empty state to display when the table is empty."
}
]
}
},
"description": ""
}
}
}

View File

@@ -0,0 +1,14 @@
{
"description": "",
"methods": [],
"displayName": "DataTableFilterBarSkeleton",
"props": {
"filterCount": {
"required": true,
"tsType": {
"name": "number"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,135 @@
{
"description": "",
"methods": [],
"displayName": "DataTableFilterDateContent",
"props": {
"id": {
"required": true,
"tsType": {
"name": "string"
},
"description": ""
},
"filter": {
"required": true,
"tsType": {
"name": "unknown"
},
"description": ""
},
"options": {
"required": true,
"tsType": {
"name": "Array",
"elements": [
{
"name": "DataTableFilterOption",
"elements": [
{
"name": "DataTableDateComparisonOperator"
}
],
"raw": "DataTableFilterOption<DataTableDateComparisonOperator>"
}
],
"raw": "DataTableFilterOption<DataTableDateComparisonOperator>[]"
},
"description": ""
},
"isCustom": {
"required": true,
"tsType": {
"name": "boolean"
},
"description": ""
},
"setIsCustom": {
"required": true,
"tsType": {
"name": "signature",
"type": "function",
"raw": "(isCustom: boolean) => void",
"signature": {
"arguments": [
{
"type": {
"name": "boolean"
},
"name": "isCustom"
}
],
"return": {
"name": "void"
}
}
},
"description": ""
},
"format": {
"defaultValue": {
"value": "\"date\"",
"computed": false
},
"description": "",
"tsType": {
"name": "union",
"raw": "\"date\" \\| \"date-time\"",
"elements": [
{
"name": "literal",
"value": "\"date\""
},
{
"name": "literal",
"value": "\"date-time\""
}
]
},
"required": false
},
"rangeOptionLabel": {
"defaultValue": {
"value": "\"Custom\"",
"computed": false
},
"description": "",
"tsType": {
"name": "string"
},
"required": false
},
"rangeOptionStartLabel": {
"defaultValue": {
"value": "\"Starting\"",
"computed": false
},
"description": "",
"tsType": {
"name": "string"
},
"required": false
},
"rangeOptionEndLabel": {
"defaultValue": {
"value": "\"Ending\"",
"computed": false
},
"description": "",
"tsType": {
"name": "string"
},
"required": false
},
"disableRangeOption": {
"defaultValue": {
"value": "false",
"computed": false
},
"description": "",
"tsType": {
"name": "boolean"
},
"required": false
}
}
}

View File

@@ -0,0 +1,6 @@
{
"description": "",
"methods": [],
"displayName": "DataTableFilterMenuSkeleton",
"props": {}
}

View File

@@ -0,0 +1,40 @@
{
"description": "",
"methods": [],
"displayName": "DataTableFilterRadioContent",
"props": {
"id": {
"required": true,
"tsType": {
"name": "string"
},
"description": ""
},
"filter": {
"required": true,
"tsType": {
"name": "unknown"
},
"description": ""
},
"options": {
"required": true,
"tsType": {
"name": "Array",
"elements": [
{
"name": "DataTableFilterOption",
"elements": [
{
"name": "string"
}
],
"raw": "DataTableFilterOption<string>"
}
],
"raw": "DataTableFilterOption<string>[]"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,50 @@
{
"description": "",
"methods": [],
"displayName": "DataTableFilterSelectContent",
"props": {
"id": {
"required": true,
"tsType": {
"name": "string"
},
"description": ""
},
"filter": {
"required": false,
"tsType": {
"name": "Array",
"elements": [
{
"name": "string"
}
],
"raw": "string[]"
},
"description": "",
"defaultValue": {
"value": "[]",
"computed": false
}
},
"options": {
"required": true,
"tsType": {
"name": "Array",
"elements": [
{
"name": "DataTableFilterOption",
"elements": [
{
"name": "string"
}
],
"raw": "DataTableFilterOption<string>"
}
],
"raw": "DataTableFilterOption<string>[]"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,6 @@
{
"description": "",
"methods": [],
"displayName": "DataTablePaginationSkeleton",
"props": {}
}

View File

@@ -0,0 +1,6 @@
{
"description": "",
"methods": [],
"displayName": "DataTableSearchSkeleton",
"props": {}
}

View File

@@ -0,0 +1,23 @@
{
"description": "",
"methods": [],
"displayName": "DataTableSelectHeader",
"props": {
"ctx": {
"required": true,
"tsType": {
"name": "DataTableHeaderContext",
"elements": [
{
"name": "TData"
},
{
"name": "unknown"
}
],
"raw": "DataTableHeaderContext<TData, unknown>"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,6 @@
{
"description": "",
"methods": [],
"displayName": "DataTableSortingMenuSkeleton",
"props": {}
}

View File

@@ -0,0 +1,18 @@
{
"description": "",
"methods": [],
"displayName": "DataTableTableSkeleton",
"props": {
"pageSize": {
"required": false,
"tsType": {
"name": "number"
},
"description": "",
"defaultValue": {
"value": "10",
"computed": false
}
}
}
}

View File

@@ -0,0 +1,29 @@
{
"description": "Toolbar shown for the data table.",
"methods": [],
"displayName": "DataTableToolbar",
"props": {
"className": {
"required": false,
"tsType": {
"name": "string"
},
"description": "Additional classes to pass to the wrapper `div` of the component."
},
"children": {
"required": false,
"tsType": {
"name": "ReactReactNode",
"raw": "React.ReactNode"
},
"description": "The children to show in the toolbar."
},
"translations": {
"required": false,
"tsType": {
"name": "DataTableToolbarTranslations"
},
"description": "The translations of strings in the toolbar."
}
}
}

View File

@@ -0,0 +1,29 @@
{
"description": "",
"methods": [],
"displayName": "DefaultEmptyStateContent",
"props": {
"heading": {
"required": false,
"tsType": {
"name": "string"
},
"description": "The heading to display in the empty state."
},
"description": {
"required": false,
"tsType": {
"name": "string"
},
"description": "The description to display in the empty state."
},
"custom": {
"required": false,
"tsType": {
"name": "ReactReactNode",
"raw": "React.ReactNode"
},
"description": "A custom component to display in the empty state, if provided it will override the heading and description."
}
}
}

View File

@@ -0,0 +1,95 @@
{
"description": "",
"methods": [],
"displayName": "OptionButton",
"props": {
"index": {
"required": true,
"tsType": {
"name": "number"
},
"description": ""
},
"option": {
"required": true,
"tsType": {
"name": "DataTableFilterOption",
"elements": [
{
"name": "union",
"raw": "string | DataTableDateComparisonOperator",
"elements": [
{
"name": "string"
},
{
"name": "DataTableDateComparisonOperator"
}
]
}
],
"raw": "DataTableFilterOption<string | DataTableDateComparisonOperator>"
},
"description": ""
},
"isSelected": {
"required": true,
"tsType": {
"name": "boolean"
},
"description": ""
},
"isFocused": {
"required": true,
"tsType": {
"name": "boolean"
},
"description": ""
},
"onClick": {
"required": true,
"tsType": {
"name": "signature",
"type": "function",
"raw": "() => void",
"signature": {
"arguments": [],
"return": {
"name": "void"
}
}
},
"description": ""
},
"onMouseEvent": {
"required": true,
"tsType": {
"name": "signature",
"type": "function",
"raw": "(idx: number) => void",
"signature": {
"arguments": [
{
"type": {
"name": "number"
},
"name": "idx"
}
],
"return": {
"name": "void"
}
}
},
"description": ""
},
"icon": {
"required": true,
"tsType": {
"name": "ReactElementType",
"raw": "React.ElementType"
},
"description": ""
}
}
}

View File

@@ -0,0 +1,6 @@
{
"description": "",
"methods": [],
"displayName": "Skeleton",
"props": {}
}

View File

@@ -57,8 +57,8 @@
},
"dependencies": {
"@emotion/is-prop-valid": "^1.3.1",
"@medusajs/icons": "~2.0.0",
"@medusajs/ui": "~4.0.0",
"@medusajs/icons": "~2.4.0",
"@medusajs/ui": "~4.0.4",
"@next/third-parties": "15.0.4",
"@octokit/request": "^8.1.1",
"@react-hook/resize-observer": "^1.2.6",

View File

@@ -12,7 +12,7 @@
"postcss.config.js"
],
"dependencies": {
"@medusajs/ui-preset": "~1.1.2",
"@medusajs/ui-preset": "~2.4.0",
"tailwindcss-animate": "^1.0.7"
},
"peerDependencies": {

File diff suppressed because it is too large Load Diff