- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
- User Guide
- Get Started
- Product
- Resources
- Tools & SDKs
- Framework
- Reference
- User Guide
DataTable
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.
Simple Example#
Products
Shirt | 10 |
Pants | 20 |
Usage#
You import the DataTable
component from @medusajs/ui
.
Columns Preparation#
Before using the DataTable
component, you need to prepare its columns using the createDataTableColumnHelper
utility:
1import {2 // ...3 createDataTableColumnHelper,4} from "@medusajs/ui"5 6const data = [7 {8 id: "1",9 title: "Shirt",10 price: 1011 },12 // other data...13]14 15const columnHelper = createDataTableColumnHelper<typeof data[0]>()16 17const columns = [18 columnHelper.accessor("title", {19 header: "Title",20 enableSorting: true,21 }),22 columnHelper.accessor("price", {23 header: "Price",24 }),25]
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.
Create Table Instance#
The DataTable
component expects a table instance created using the useDataTable
hook. Import that hook from @medusajs/ui
:
Then, inside the component that will render DataTable
, create a table instance using the useDataTable
hook:
The useDataTable
hook accepts an object with the following properties:
columns
: An array of column configurations generated using thecreateDataTableColumnHelper
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:
In the DataTable
component, you pass the following child components:
DataTable.Toolbar
: The toolbar component shown at the top of the table. You can also add buttons for custom actions.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#
DataTable
This component creates a data table with filters, pagination, sorting, and more.
It's built on top of the Table
component while expanding its functionality.
The DataTable
is useful to create tables similar to those in the Medusa Admin dashboard.
Prop | Type | Default |
---|---|---|
instance | UseDataTableReturn | - |
children | ReactReactNode | - |
className | string | - |
DataTable.Table
This component renders the table in a data table, supporting advanced features.
Prop | Type | Default |
---|---|---|
emptyState | object | - |
DataTable.Pagination
This component adds a pagination component and functionality to the data table.
Prop | Type | Default |
---|---|---|
translations | ReactComponentProps["translations"] | - |
DataTable.FilterMenu
This component adds a filter menu to the data table, allowing users to filter the table's data.
Prop | Type | Default |
---|---|---|
tooltip | string | - |
DataTable.Search
This component adds a search input to the data table, allowing users to search through the table's data.
Prop | Type | Default |
---|---|---|
autoFocus | boolean | - |
className | string | - |
placeholder | string | - |
DataTable.CommandBar
This component adds a command bar to the data table, which is used to show commands that can be executed on the selected rows.
Prop | Type | Default |
---|---|---|
selectedLabel | unknown | string | - |
DataTable.SortingMenu
This component adds a sorting menu to the data table, allowing users to sort the table's data.
Prop | Type | Default |
---|---|---|
tooltip | string | - |
Example with Data Fetching#
Refer to this Admin Components guide for an example on using the DataTable
component with data fetching from the Medusa application.
Configure Cell Rendering#
Products
Status | ||
---|---|---|
Shirt | 10 | |
Pants | 20 |
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:
1const products = [2 {3 id: "1",4 title: "Shirt",5 price: 10,6 is_active: true7 },8 {9 id: "2",10 title: "Pants",11 price: 20,12 is_active: true13 }14]15 16const columnHelper = createDataTableColumnHelper<typeof products[0]>()17 18const columns = [19 columnHelper.accessor("is_active", {20 header: "Status",21 cell: ({ getValue }) => {22 const isActive = getValue()23 return (24 <Badge color={isActive ? "green" : "grey"}>25 {isActive ? "Active" : "Inactive"}26 </Badge>27 )28 }29 }),30 // ...31]
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#
Products
Shirt | 10 |
Pants | 20 |
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:
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:
1const [search, setSearch] = useState<string>("")2 3const shownProducts = useMemo(() => {4 return products.filter((product) => product.title.toLowerCase().includes(search.toLowerCase()))5}, [search]) 6 7const table = useDataTable({8 columns,9 data: shownProducts,10 getRowId: (product) => product.id,11 rowCount: products.length,12 isLoading: false,13 // Pass the state and onSearchChange to the table instance.14 search: {15 state: search,16 onSearchChange: setSearch17 }18})
Then, render the DataTable.Search
component as part of the DataTable
's children:
1return (2 <DataTable instance={table}>3 <DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">4 <Heading>Products</Heading>5 {/* This component renders the search bar */}6 <DataTable.Search placeholder="Search..." />7 </DataTable.Toolbar>8 <DataTable.Table />9 </DataTable>10)
This will show a search input at the top of the table, in the data table's toolbar.
DataTable with Pagination#
Products
Shirt | 10 |
Pants | 20 |
Hat | 15 |
Socks | 5 |
Shoes | 50 |
Jacket | 100 |
Scarf | 25 |
Gloves | 12 |
Belt | 18 |
Sunglasses | 30 |
1
10 of 17 results
1 of 2 pages
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
:
Then, create a state variable to manage the pagination:
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 be0
.
Next, pass the pagination object to the useDataTable
hook:
pagination
accepts the following properties:
state
: The pagination state object. This must be a React state variable of typeDataTablePaginationState
.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:
1const [pagination, setPagination] = useState<DataTablePaginationState>({2 pageSize: PAGE_SIZE,3 pageIndex: 0,4})5 6const shownProducts = useMemo(() => {7 return products.slice(8 pagination.pageIndex * pagination.pageSize,9 (pagination.pageIndex + 1) * pagination.pageSize10 )11}, [pagination])12 13const table = useDataTable({14 data: shownProducts,15 columns,16 rowCount: products.length,17 getRowId: (product) => product.id,18 pagination: {19 // Pass the pagination state and updater to the table instance20 state: pagination,21 onPaginationChange: setPagination,22 },23 isLoading: false,24});
Finally, render the DataTable.Pagination
component as part of the DataTable
's children:
This will show the pagination controls at the end of the table.
DataTable with Filters#
Products
Shirt | 10 |
Pants | 20 |
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:
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:
DataTable
component.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 isselect
orradio
, an array of dropdown options. Each option has alabel
andvalue
property.
Next, in the component rendering the DataTable
component, create a state variable to manage the filtering, and pass the filters to the useDataTable
hook:
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.
The useDataTable
hook accepts the following properties for filtering:
filters
: An array of filter configurations generated using thecreateDataTableFilterHelper
utility.filtering
: An object with the following properties:state
: The filtering state object. This must be a React state variable of typeDataTableFilteringState
.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:
1const [filtering, setFiltering] = useState<DataTableFilteringState>({})2 3const shownProducts = useMemo(() => {4 return products.filter((product) => {5 return Object.entries(filtering).every(([key, value]) => {6 if (!value) {7 return true8 }9 if (typeof value === "string") {10 // @ts-ignore11 return product[key].toString().toLowerCase().includes(value.toString().toLowerCase())12 }13 if (Array.isArray(value)) {14 // @ts-ignore15 return value.includes(product[key].toLowerCase())16 }17 if (typeof value === "object") {18 // @ts-ignore19 const date = new Date(product[key])20 let matching = false21 if ("$gte" in value && value.$gte) {22 matching = date >= new Date(value.$gte as number)23 }24 if ("$lte" in value && value.$lte) {25 matching = date <= new Date(value.$lte as number)26 }27 if ("$lt" in value && value.$lt) {28 matching = date < new Date(value.$lt as number)29 }30 if ("$gt" in value && value.$gt) {31 matching = date > new Date(value.$gt as number)32 }33 return matching34 }35 })36 })37}, [filtering])38 39const table = useDataTable({40 data: shownProducts,41 columns,42 getRowId: (product) => product.id,43 rowCount: products.length,44 isLoading: false,45 filtering: {46 state: filtering,47 onFilteringChange: setFiltering,48 },49 filters50})
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.
Finally, render the DataTable.FilterMenu
component as part of the DataTable
's children:
1return (2 <DataTable instance={table}>3 <DataTable.Toolbar className="flex justify-between items-center">4 <Heading>Products</Heading>5 {/** This component will render a menu that allows the user to choose which filters to apply to the table data. **/}6 <DataTable.FilterMenu tooltip="Filter" />7 </DataTable.Toolbar>8 <DataTable.Table />9 </DataTable>10)
This will show a filter menu at the top of the table, in the data table's toolbar.
Filtering Date Values#
Products
Created At | ||
---|---|---|
Shirt | 10 | 2/27/2025, 2:56:04 PM |
Pants | 20 | 1/1/2026, 12:00:00 AM |
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:
1const filters = [2 // ...3 filterHelper.accessor("created_at", {4 type: "date",5 label: "Created At",6 format: "date",7 formatDateValue: (date) => date.toLocaleString(),8 rangeOptionStartLabel: "From",9 rangeOptionEndLabel: "To",10 rangeOptionLabel: "Between",11 options: [12 {13 label: "Today",14 value: {15 $gte: new Date(new Date().setHours(0, 0, 0, 0)).toString(),16 $lte: new Date(new Date().setHours(23, 59, 59, 999)).toString()17 }18 },19 {20 label: "Yesterday",21 value: {22 $gte: new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000).toString(),23 $lte: new Date(new Date().setHours(0, 0, 0, 0)).toString()24 }25 },26 {27 label: "Last Week",28 value: {29 $gte: new Date(new Date().setHours(0, 0, 0, 0) - 7 * 24 * 60 * 60 * 1000).toString(),30 $lte: new Date(new Date().setHours(0, 0, 0, 0)).toString()31 },32 },33 ]34 }),35]
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 eitherdate
to filter by dates, ordatetime
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 alabel
andvalue
property. Thevalue
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:
1const shownProducts = useMemo(() => {2 return products.filter((product) => {3 return Object.entries(filtering).every(([key, value]) => {4 if (!value) {5 return true6 }7 // other types checks...8 if (typeof value === "object") {9 // @ts-ignore10 const date = new Date(product[key])11 let matching = false12 if ("$gte" in value && value.$gte) {13 matching = date >= new Date(value.$gte as number)14 }15 if ("$lte" in value && value.$lte) {16 matching = date <= new Date(value.$lte as number)17 }18 if ("$lt" in value && value.$lt) {19 matching = date < new Date(value.$lt as number)20 }21 if ("$gt" in value && value.$gt) {22 matching = date > new Date(value.$gt as number)23 }24 return matching25 }26 })27 })28}, [filtering])
Initial Filter Values#
Products
Shirt | 10 |
If you want to set initial filter values, you can set the initial state of the filtering
state variable:
The user can still change the filter values, but the initial values will be applied when the table is first rendered.
DataTable with Sorting#
Products
Price | |
---|---|
Shirt | 10 |
Pants | 20 |
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:
1const columns = [2 columnHelper.accessor("title", {3 header: "Title",4 // Enables sorting for the column.5 enableSorting: true,6 // If omitted, the header will be used instead if it's a string, 7 // otherwise the accessor key (id) will be used.8 sortLabel: "Title",9 // If omitted the default value will be "A-Z"10 sortAscLabel: "A-Z",11 // If omitted the default value will be "Z-A"12 sortDescLabel: "Z-A",13 }),14]
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, theheader
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 beA-Z
.sortDescLabel
: The label text for the descending sort button. If omitted, the default value will beZ-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:
1import {2 // ...3 DataTableSortingState4} from "@medusajs/ui"5 6export default function ProductTable () {7 const [sorting, setSorting] = useState<DataTableSortingState | null>(null);8 9 const table = useDataTable({10 // ...11 sorting: {12 state: sorting,13 onSortingChange: setSorting,14 },15 })16 17 // ...18}
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.
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 typeDataTableSortingState
.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:
1const [sorting, setSorting] = useState<DataTableSortingState | null>(null);2 3const shownProducts = useMemo(() => {4 if (!sorting) {5 return products6 }7 return products.slice().sort((a, b) => {8 // @ts-ignore9 const aVal = a[sorting.id]10 // @ts-ignore11 const bVal = b[sorting.id]12 if (aVal < bVal) {13 return sorting.desc ? 1 : -114 }15 if (aVal > bVal) {16 return sorting.desc ? -1 : 117 }18 return 019 })20}, [sorting])21 22const table = useDataTable({23 data: shownProducts,24 columns,25 getRowId: (product) => product.id,26 rowCount: products.length,27 sorting: {28 // Pass the pagination state and updater to the table instance29 state: sorting,30 onSortingChange: setSorting,31 },32 isLoading: false,33})
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:
1return (2 <DataTable instance={table}>3 <DataTable.Toolbar className="flex justify-between items-center">4 <Heading>Products</Heading>5 {/** This component will render a menu that allows the user to choose which column to sort by and in what direction. **/}6 <DataTable.SortingMenu tooltip="Sort" />7 </DataTable.Toolbar>8 <DataTable.Table />9 </DataTable>10)
This will show a sorting menu at the top of the table, in the data table's toolbar.
Initial Sort Values#
Products
Price | |
---|---|
Pants | 20 |
Shirt | 10 |
If you want to set initial sort values, you can set the initial state of the sorting
state variable:
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#
Products
Shirt | 10 | |
Pants | 20 |
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
:
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:
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:
DataTable
component.1const commandHelper = createDataTableCommandHelper()2 3const useCommands = () => {4 return [5 commandHelper.command({6 label: "Delete",7 shortcut: "D",8 action: async (selection) => {9 const productsToDeleteIds = Object.keys(selection)10 11 // TODO remove products from the server12 }13 })14 ]15}
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'sid
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:
1const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>({})2 3const commands = useCommands()4 5const instance = useDataTable({6 data: products,7 columns,8 getRowId: (product) => product.id,9 rowCount: products.length,10 isLoading: false,11 commands,12 rowSelection: {13 state: rowSelection,14 onRowSelectionChange: setRowSelection,15 },16})
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 thecreateDataTableCommandHelper
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 typeDataTableRowSelectionState
.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:
1return (2 <DataTable instance={instance}>3 <DataTable.Toolbar className="flex justify-between items-center">4 <Heading>Products</Heading>5 </DataTable.Toolbar>6 <DataTable.Table />7 {/** This component will the command bar when the user has selected at least one row. **/}8 <DataTable.CommandBar selectedLabel={(count) => `${count} selected`} />9 </DataTable>10)
This will show a command bar when the user has selected at least one row in the table.