1 ---
2 sidebar_label: "Table"
3 ---
4
5 import { TypeList } from "docs-ui"
6
7 export const metadata = {
8 title: `Table - Admin Components`,
9 }
10
11 # {metadata.title}
12
13 <Note>
14
15 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 as it provides features for sorting, filtering, pagination, and more with a simpler API.
16
17 </Note>
18
19 You can use the `Table` component from Medusa UI to display data in a table. It's mostly recommended for simpler tables.
20
21 To create a component that shows a table with pagination, create the file `src/admin/components/table.tsx` with the following content:
22
23 ```tsx title="src/admin/components/table.tsx"
24 import { useMemo } from "react"
25 import { Table as UiTable } from "@medusajs/ui"
26
27 export type TableProps = {
28 columns: {
29 key: string
30 label?: string
31 render?: (value: unknown) => React.ReactNode
32 }[]
33 data: Record<string, unknown>[]
34 pageSize: number
35 count: number
36 currentPage: number
37 setCurrentPage: (value: number) => void
38 }
39
40 export const Table = ({
41 columns,
42 data,
43 pageSize,
44 count,
45 currentPage,
46 setCurrentPage,
47 }: TableProps) => {
48 const pageCount = useMemo(() => {
49 return Math.ceil(count / pageSize)
50 }, [data, pageSize])
51
52 const canNextPage = useMemo(() => {
53 return currentPage < pageCount - 1
54 }, [currentPage, pageCount])
55 const canPreviousPage = useMemo(() => {
56 return currentPage - 1 >= 0
57 }, [currentPage])
58
59 const nextPage = () => {
60 if (canNextPage) {
61 setCurrentPage(currentPage + 1)
62 }
63 }
64
65 const previousPage = () => {
66 if (canPreviousPage) {
67 setCurrentPage(currentPage - 1)
68 }
69 }
70
71 return (
72 <div className="flex h-full flex-col overflow-hidden !border-t-0">
73 <UiTable>
74 <UiTable.Header>
75 <UiTable.Row>
76 {columns.map((column, index) => (
77 <UiTable.HeaderCell key={index}>
78 {column.label || column.key}
79 </UiTable.HeaderCell>
80 ))}
81 </UiTable.Row>
82 </UiTable.Header>
83 <UiTable.Body>
84 {data.map((item, index) => {
85 const rowIndex = "id" in item ? item.id as string : index
86 return (
87 <UiTable.Row key={rowIndex}>
88 {columns.map((column, index) => (
89 <UiTable.Cell key={`${rowIndex}-${index}`}>
90 <>
91 {column.render && column.render(item[column.key])}
92 {!column.render && (
93 <>{item[column.key] as string}</>
94 )}
95 </>
96 </UiTable.Cell>
97 ))}
98 </UiTable.Row>
99 )
100 })}
101 </UiTable.Body>
102 </UiTable>
103 <UiTable.Pagination
104 count={count}
105 pageSize={pageSize}
106 pageIndex={currentPage}
107 pageCount={pageCount}
108 canPreviousPage={canPreviousPage}
109 canNextPage={canNextPage}
110 previousPage={previousPage}
111 nextPage={nextPage}
112 />
113 </div>
114 )
115 }
116 ```
117
118 The `Table` component uses the component from the [UI package](!ui!/components/table), with additional styling and rendering of data.
119
120 It accepts the following props:
121
122 <TypeList
123 types={[
124 {
125 name: "columns",
126 type: "`object[]`",
127 optional: false,
128 description: "The table's columns.",
129 children: [
130 {
131 name: "key",
132 type: "`string`",
133 optional: false,
134 description: "The column's key in the passed `data`"
135 },
136 {
137 name: "label",
138 type: "`string`",
139 optional: true,
140 description: "The column's label shown in the table. If not provided, the `key` is used."
141 },
142 {
143 name: "render",
144 type: "`(value: unknown) => React.ReactNode`",
145 optional: true,
146 description: "By default, the data is shown as-is in the table. You can use this function to change how the value is rendered. The function receives the value is a parameter and returns a React node."
147 }
148 ]
149 },
150 {
151 name: "data",
152 type: "`Record<string, unknown>[]`",
153 optional: false,
154 description: "The data to show in the table for the current page. The keys of each object should be in the `columns` array."
155 },
156 {
157 name: "pageSize",
158 type: "`number`",
159 optional: false,
160 description: "The number of items to show per page."
161 },
162 {
163 name: "count",
164 type: "`number`",
165 optional: false,
166 description: "The total number of items."
167 },
168 {
169 name: "currentPage",
170 type: "`number`",
171 optional: false,
172 description: "A zero-based index indicating the current page's number."
173 },
174 {
175 name: "setCurrentPage",
176 type: "`(value: number) => void`",
177 optional: false,
178 description: "A function used to change the current page."
179 }
180 ]}
181 />
182
183 ---
184
185 ## Example
186
187 Use the `Table` component in any widget or UI route.
188
189 For example, create the widget `src/admin/widgets/product-widget.tsx` with the following content:
190
191 ```tsx title="src/admin/widgets/product-widget.tsx"
192 import { defineWidgetConfig } from "@medusajs/admin-sdk"
193 import { StatusBadge } from "@medusajs/ui"
194 import { Table } from "../components/table"
195 import { useState } from "react"
196 import { Container } from "../components/container"
197
198 const ProductWidget = () => {
199 const [currentPage, setCurrentPage] = useState(0)
200
201 return (
202 <Container>
203 <Table
204 columns={[
205 {
206 key: "name",
207 label: "Name",
208 },
209 {
210 key: "is_enabled",
211 label: "Status",
212 render: (value: unknown) => {
213 const isEnabled = value as boolean
214
215 return (
216 <StatusBadge color={isEnabled ? "green" : "grey"}>
217 {isEnabled ? "Enabled" : "Disabled"}
218 </StatusBadge>
219 )
220 },
221 },
222 ]}
223 data={[
224 {
225 name: "John",
226 is_enabled: true,
227 },
228 {
229 name: "Jane",
230 is_enabled: false,
231 },
232 ]}
233 pageSize={2}
234 count={2}
235 currentPage={currentPage}
236 setCurrentPage={setCurrentPage}
237 />
238 </Container>
239 )
240 }
241
242 export const config = defineWidgetConfig({
243 zone: "product.details",
244 })
245
246 export default ProductWidget
247 ```
248
249 This widget also uses the [Container](../container/page.mdx) custom component.
250
251 ---
252
253 ## Example With Data Fetching
254
255 This section shows you how to use the `Table` component when fetching data from the Medusa application's API routes.
256
257 Assuming you've set up the JS SDK as explained in [this guide](../../../js-sdk/page.mdx), create the UI route `src/admin/routes/custom/page.tsx` with the following content:
258
259 export const tableExampleHighlights = [
260 ["12", "currentPage", "The table's current page."],
261 ["13", "limit", "The maximum number of items per page."],
262 ["14", "offset", "The number of items to skip before retrieving the current page's items."],
263 ["18", "data", "The response fields."],
264 ["18", "useQuery", "Fetch products from the Medusa application."]
265 ]
266
267 ```tsx title="src/admin/routes/custom/page.tsx" collapsibleLines="1-10" expandButtonLabel="Show Imports" highlights={tableExampleHighlights}
268 import { defineRouteConfig } from "@medusajs/admin-sdk"
269 import { ChatBubbleLeftRight } from "@medusajs/icons"
270 import { useQuery } from "@tanstack/react-query"
271 import { SingleColumnLayout } from "../../layouts/single-column"
272 import { Table } from "../../components/table"
273 import { sdk } from "../../lib/config"
274 import { useMemo, useState } from "react"
275 import { Container } from "../../components/container"
276 import { Header } from "../../components/header"
277
278 const CustomPage = () => {
279 const [currentPage, setCurrentPage] = useState(0)
280 const limit = 15
281 const offset = useMemo(() => {
282 return currentPage * limit
283 }, [currentPage])
284
285 const { data } = useQuery({
286 queryFn: () => sdk.admin.product.list({
287 limit,
288 offset,
289 }),
290 queryKey: [["products", limit, offset]],
291 })
292
293 // TODO display table
294 }
295
296 export const config = defineRouteConfig({
297 label: "Custom",
298 icon: ChatBubbleLeftRight,
299 })
300
301 export default CustomPage
302 ```
303
304 In the `CustomPage` component, you define:
305
306 - A state variable `currentPage` that stores the current page of the table.
307 - A `limit` variable, indicating how many items to retrieve per page
308 - An `offset` memoized variable indicating how many items to skip before the retrieved items. It's calculated as a multiplication of `currentPage` and `limit`.
309
310 Then, you use `useQuery` from [Tanstack Query](https://tanstack.com/query/latest) to retrieve products using the JS SDK. You pass `limit` and `offset` as query parameters, and you set the `queryKey`, which is used for caching and revalidation, to be based on the key `products`, along with the current limit and offset. So, whenever the `offset` variable changes, the request is sent again to retrieve the products of the current page.
311
312 <Note title="Tip">
313
314 You can change the query to send a request to a custom API route as explained in [this guide](../../../js-sdk/page.mdx#send-requests-to-custom-routes).
315
316 </Note>
317
318 <Note type="warning">
319
320 Do not install Tanstack Query as that will cause unexpected errors in your development. If you prefer installing it for better auto-completion in your code editor, make sure to install `v5.64.2` as a development dependency.
321
322 </Note>
323
324 `useQuery` returns an object containing `data`, which holds the response fields including the products and pagination fields.
325
326 Then, to display the table, replace the `TODO` with the following:
327
328 ```tsx
329 return (
330 <SingleColumnLayout>
331 <Container>
332 <Header title="Products" />
333 {data && (
334 <Table
335 columns={[
336 {
337 key: "id",
338 label: "ID",
339 },
340 {
341 key: "title",
342 label: "Title",
343 },
344 ]}
345 data={data.products as any}
346 pageSize={data.limit}
347 count={data.count}
348 currentPage={currentPage}
349 setCurrentPage={setCurrentPage}
350 />
351 )}
352 </Container>
353 </SingleColumnLayout>
354 )
355 ```
356
357 Aside from the `Table` component, this UI route also uses the [LayoutComposer](../../layouts/layout-composer/page.mdx), [Container](../container/page.mdx), and [Header](../header/page.mdx) custom component.
358
359 If `data` isn't `undefined`, you display the `Table` component passing it the following props:
360
361 - `columns`: The columns to show. You only show the product's ID and title.
362 - `data`: The rows of the table. You pass it the `products` property of `data`.
363 - `pageSize`: The maximum number of items per page. You pass it the `count` property of `data`.
364 - `currentPage` and `setCurrentPage`: The current page and the function to change it.
365
366 To test it out, log into the Medusa Admin and open `http://localhost:9000/app/custom`. You'll find a table of products with pagination.