Write a cell type
Pick the lightest way to change how a column shows and edits values, then write a custom cell type with its own display, editor, and text round trip.
Most column needs end before a custom cell type. Take the first step that fits.
Format the display
A number column formats its value with options.format, which takes any Intl.NumberFormat options. options.locale sets the language, and it defaults to the locale of the grid. Copy, export, sort, and the editor keep the raw number:
import { defineColumns } from "@/components/data-grid/data-grid";
type Product = { id: string; price: number; margin: number };
export const columns = defineColumns<Product>()([
{
id: "price",
header: "Price",
accessorKey: "price",
type: "number",
options: {
format: { style: "currency", currency: "EUR" },
locale: "de-DE",
},
},
{
id: "margin",
header: "Margin",
accessorKey: "margin",
type: "number",
options: { format: { style: "percent", maximumFractionDigits: 1 } },
},
] as const);Use a built-in type
urlshows a safe link.options.labelmaps the URL to the shown text.longTextstores multi-line text and edits it in a popover.select,date, andcheckboxcover choices, dates, and booleans.
Built-in cell types lists every type and its options.
Define a custom type
If the stored value, the editor, or the text round trip differs from every built-in, write your own type. The sample builds a money type that stores a plain number | null, shows a formatted amount, and reads a pasted $1,234.56 as 1234.56.
- Declare the key in
GridCellTypes, sodefineColumnstypes the column value and options. - Write
toTextfor copy and export. Keep it plain and parseable. - Write
toDisplayTextfor the formatted text. Print, column autosize, and the set values of the header filter use it, and usetoTextwithout it. When the numbers of a selection come from one column, the status bar formats its sum, average, minimum, and maximum with it.Celldecides what the cell itself shows. - Write
fromTextfor paste and typing. For text it cannot parse, callrejectText(). The cell keeps its value, and the grid reports the text. ReturnclearValue()only to empty the cell on purpose. - Write
CellandEditor. Start the editor fromuseCellEditor. It owns the draft and the focus, commits on Enter and on blur, and cancels on Escape. - Register the type in
cellTypesunder the name that a column uses intype.
The sample does all six steps:
"use client";
import {
DataGrid,
defineCellType,
defineColumns,
rejectText,
useCellEditor,
type CellEditorProps,
type CellRenderProps,
} from "@/components/data-grid/data-grid";
import { Input } from "@/components/ui/input";
declare module "@/components/data-grid/types" {
interface GridCellTypes {
money: { value: number | null; options: { currency: string } };
}
}
type Options = { currency: string };
const formatters = new Map<string, Intl.NumberFormat>();
function format(value: number | null, options?: Options): string {
if (value === null) return "";
const currency = options?.currency ?? "USD";
let formatter = formatters.get(currency);
if (!formatter) {
formatter = new Intl.NumberFormat("en-US", { style: "currency", currency });
formatters.set(currency, formatter);
}
return formatter.format(value);
}
function parse(text: string): number | null {
const kept = text.replace(/[^0-9.,-]/g, "");
const groupsThousands = kept.includes(".") || /,\d{3}(?!\d)/.test(kept);
const plain = groupsThousands
? kept.replace(/,/g, "")
: kept.replace(",", ".");
const amount = Number(plain);
return plain === "" || Number.isNaN(amount) ? null : amount;
}
type Value = number | null;
function fromText(text: string): Value {
return text.trim() === "" ? null : (parse(text) ?? rejectText());
}
function Cell({ value, options }: CellRenderProps<unknown, Value, Options>) {
return (
<span className="block truncate tabular-nums">
{format(value, options)}
</span>
);
}
function Editor(props: CellEditorProps<unknown, Value, Options>) {
const { ref, ...bindings } = useCellEditor(props, {
toDraft: (value) => (value === null ? "" : String(value)),
});
return <Input ref={ref} {...bindings} className="h-full text-end" />;
}
const moneyCellType = defineCellType("money", {
Cell,
Editor,
toText: (value) => (value === null ? "" : String(value)),
toDisplayText: format,
fromText,
clearValue: () => null,
isEmpty: (value) => value === null,
compare: (a, b) => (a ?? 0) - (b ?? 0),
align: "end",
});
type Product = { id: string; name: string; price: number | null };
const columns = defineColumns<Product>()([
{ id: "name", header: "Name", accessorKey: "name", type: "text" },
{
id: "price",
header: "Price",
accessorKey: "price",
type: "money",
options: { currency: "EUR" },
},
] as const);
export function Products({ products }: { products: Product[] }) {
return (
<DataGrid
defaultData={products}
columns={columns}
cellTypes={{ money: moneyCellType }}
/>
);
}The cellTypes prop merges over the built-ins, so the text column keeps working. A key that names a built-in replaces it, and a key set to null removes the type. An inline cellTypes object is safe: when an entry changes identity, the grid resolves the types again. Define each cell type outside the component, so its identity stays stable. A column whose type has no registry entry renders as text and drops its edits. The console warns in development.
The sample keeps these rules:
- It caches the
Intl.NumberFormatby currency, so scrolling builds no formatter per cell. - It pins the locale to
"en-US". A default locale can differ between server and browser, which causes a hydration mismatch.
Result
The Price column shows €1,234.56 for the value 1234.56. A paste of $1,234.56 stores 1234.56, and a copy gives 1234.56. Without a point, a comma before exactly three digits groups thousands, so $1,234 stores 1234. Any other comma is the decimal separator, so 1,5 stores 1.5.
Test the type
toText, fromText, isEmpty, and compare are plain functions. Test them without rendering: fromText("$1,234.56") gives 1234.56, and fromText("not a price") rejects the text.
Related
- Cell type model: how the grid uses each member of a cell type.
- Cell type contract: every member, option, and editor rule.
- Built-in cell types: the types that ship with the grid.
- Custom cell type example: the currency type as a live demo with
data-grid-custom-cell-demo. - Plan a cell type: choose the members before you write one.