DataTable
Displays tabular data such as sales figures in rows and columns, with sortable headings and a totals row, for comparing numbers rather than acting on individual records.
Preview
Code
Example.jsx
import { useState, useCallback, useMemo } from 'react';
import { Card, Text, DataTable } from '@shopify/polaris';
const PRODUCT_SALES = [
{ product: 'Ceramic pour-over kettle', sku: 'KET-1001', price: 89, orders: 312, net: 27768 },
{ product: 'Cold brew carafe, 1L', sku: 'CAR-2204', price: 42, orders: 508, net: 21336 },
{ product: 'Single-origin sampler', sku: 'SMP-0412', price: 28, orders: 947, net: 26516 },
{ product: 'Burr grinder, matte black', sku: 'GRD-3310', price: 165, orders: 184, net: 30360 },
{ product: 'Reusable paper filters', sku: 'FLT-0090', price: 12, orders: 1264, net: 15168 },
{ product: 'Espresso tamper, walnut', sku: 'TMP-7720', price: 34, orders: 221, net: 7514 },
];
const SORT_KEYS = ['product', 'sku', 'price', 'orders', 'net'];
const COLUMN_TYPES = ['text', 'text', 'numeric', 'numeric', 'numeric'];
const HEADINGS = ['Product', 'SKU', 'Price', 'Orders', 'Net sales'];
const SORTABLE_COLUMNS = [true, false, true, true, true];
const INITIAL_SORT_INDEX = 4;
const formatMoney = (value) =>
`$${value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
const compareBy = (key, direction) => (first, second) => {
const a = first[key];
const b = second[key];
const result = typeof a === 'number' ? a - b : String(a).localeCompare(String(b));
return direction === 'descending' ? -result : result;
};
export const Example = () => {
const [sortIndex, setSortIndex] = useState(INITIAL_SORT_INDEX);
const [sortDirection, setSortDirection] = useState('descending');
const handleSort = useCallback((index, direction) => {
setSortIndex(index);
setSortDirection(direction);
}, []);
const rows = useMemo(() => {
const sorted = [...PRODUCT_SALES].sort(compareBy(SORT_KEYS[sortIndex], sortDirection));
return sorted.map((item) => [
item.product,
item.sku,
formatMoney(item.price),
item.orders.toLocaleString('en-US'),
formatMoney(item.net),
]);
}, [sortIndex, sortDirection]);
const totals = useMemo(() => {
const orders = PRODUCT_SALES.reduce((sum, item) => sum + item.orders, 0);
const net = PRODUCT_SALES.reduce((sum, item) => sum + item.net, 0);
return ['', '', '', orders.toLocaleString('en-US'), formatMoney(net)];
}, []);
return (
<Card padding="0">
<DataTable
columnContentTypes={COLUMN_TYPES}
headings={HEADINGS}
rows={rows}
totals={totals}
totalsName={{ singular: 'Net sales', plural: 'Net sales' }}
showTotalsInFooter
sortable={SORTABLE_COLUMNS}
defaultSortDirection="descending"
initialSortColumnIndex={INITIAL_SORT_INDEX}
onSort={handleSort}
footerContent={
<Text as="span" variant="bodySm" tone="subdued">
Sorted by {HEADINGS[sortIndex].toLowerCase()}, {sortDirection}
</Text>
}
/>
</Card>
);
};